├── __init__.py ├── .gitattributes ├── MANIFEST.in ├── .gitignore ├── MANIFEST ├── collateral ├── abc_test.empty.bam ├── good_close_range.png ├── good_long_range.png ├── PGBlueLogoHorSmall.png ├── thresholds.json ├── style.css └── HiC_QC_report_template.md ├── tests ├── collateral │ └── input │ │ ├── abc_test.bam │ │ ├── abc_test.bam.bai │ │ ├── abc_test.empty.bam │ │ ├── interleaved_header.bam │ │ ├── abc_test.mem2.nosamblaster.bam │ │ ├── abc_test.mem2.nosamblaster.bam.bai │ │ ├── abc_test.empty.bam.bai │ │ └── interleaved_header.bam.bai └── test_hic_qc.py ├── env.minimal.yml ├── AUTHORS ├── pyproject.toml ├── .travis.yml ├── env.yml ├── ChangeLog ├── Readme.md ├── LICENSE └── hic_qc.py /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | _version.py export-subst 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include versioneer.py 2 | include _version.py 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info/ 3 | dist/ 4 | build/ 5 | bash/ 6 | -------------------------------------------------------------------------------- /MANIFEST: -------------------------------------------------------------------------------- 1 | # file GENERATED by distutils, do NOT edit 2 | _version.py 3 | setup.cfg 4 | setup.py 5 | versioneer.py 6 | -------------------------------------------------------------------------------- /collateral/abc_test.empty.bam: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/collateral/abc_test.empty.bam -------------------------------------------------------------------------------- /collateral/good_close_range.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/collateral/good_close_range.png -------------------------------------------------------------------------------- /collateral/good_long_range.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/collateral/good_long_range.png -------------------------------------------------------------------------------- /collateral/PGBlueLogoHorSmall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/collateral/PGBlueLogoHorSmall.png -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.bam: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/abc_test.bam -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.bam.bai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/abc_test.bam.bai -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.empty.bam: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/abc_test.empty.bam -------------------------------------------------------------------------------- /tests/collateral/input/interleaved_header.bam: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/interleaved_header.bam -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.mem2.nosamblaster.bam: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/abc_test.mem2.nosamblaster.bam -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.mem2.nosamblaster.bam.bai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phasegenomics/hic_qc/HEAD/tests/collateral/input/abc_test.mem2.nosamblaster.bam.bai -------------------------------------------------------------------------------- /env.minimal.yml: -------------------------------------------------------------------------------- 1 | channels: 2 | - conda-forge 3 | - bioconda 4 | - nodefaults 5 | dependencies: 6 | - markdown 7 | - matplotlib 8 | - numpy 9 | - python-pdfkit 10 | - pysam 11 | - python=3.12 12 | - scipy 13 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Brad Nelson 2 | Brad Nelson 3 | EC2 Default User 4 | Maximilian Press 5 | Shawn Sullivan 6 | maximilianpress 7 | shawnpg 8 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "hic_qc" 3 | description = "Quality assessment for Hi-C libraries" 4 | dynamic = ["version"] 5 | 6 | [build-system] 7 | requires = ["setuptools >= 64.0.0", "setuptools-git-versioning<2"] 8 | build-backend = "setuptools.build_meta" 9 | 10 | [tool.setuptools.packages.find] 11 | where = ["."] 12 | 13 | [tool.setuptools-git-versioning] 14 | enabled = true 15 | template = "v{tag}" 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: generic 2 | env: 3 | - PYTHON="default" 4 | before_install: 5 | - sudo apt-get update 6 | - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; 7 | - bash miniconda.sh -b -p $HOME/miniconda 8 | - export PATH="$HOME/miniconda/bin:$PATH" 9 | - hash -r 10 | - conda config --set always_yes yes --set changeps1 no 11 | - conda update -q conda 12 | install: 13 | # Useful for debugging any issues with conda 14 | - conda info -a 15 | # Replace dep1 dep2 ... with your dependencies 16 | - conda env create -n test-environment --file env.minimal.yml; 17 | - source activate test-environment 18 | - python --version 19 | - pip install --no-deps -e . 20 | script: 21 | - python -m unittest discover tests 22 | -------------------------------------------------------------------------------- /collateral/thresholds.json: -------------------------------------------------------------------------------- 1 | { 2 | "genome" : { 3 | "MIN_SAME_STRAND_HQ_PERCENTAGE" : "0.015", 4 | "MIN_INFORMATIVE_READ_PAIRS_PERCENTAGE" : "0.05", 5 | "MAX_NONINFORMATIVE_READ_PAIR_PERCENTAGE" : "0.50", 6 | "MIN_LONG_CONTACT_PERCENTAGE" : "0.03", 7 | "MIN_INTERCONTIG_CONTACT_PERCENTAGE" : "0.025", 8 | "MIN_USABLE_READS_PER_CONTIG" : "600", 9 | "MIN_USABLE_READS_PER_CONTIG_PER_MILLION" : "100", 10 | "MAX_DUPE_PERCENTAGE" : "0.40", 11 | "MAX_ZERO_DIST_PERCENTAGE" : "0.20", 12 | "MAX_ZERO_MAPQ0_PERCENTAGE" : "0.20", 13 | "MAX_UNMAPPED_PERCENTAGE" : "0.10" 14 | }, 15 | "metagenome" : { 16 | "MIN_SAME_STRAND_HQ_PERCENTAGE" : "0.0", 17 | "MIN_INFORMATIVE_READ_PAIRS_PERCENTAGE" : "0.10", 18 | "MAX_NONINFORMATIVE_READ_PAIR_PERCENTAGE" : "0.50", 19 | "MIN_LONG_CONTACT_PERCENTAGE" : "0.0", 20 | "MIN_INTERCONTIG_CONTACT_PERCENTAGE" : "0.05", 21 | "MIN_USABLE_READS_PER_CONTIG" : "600", 22 | "MIN_USABLE_READS_PER_CONTIG_PER_MILLION" : "100", 23 | "MAX_DUPE_PERCENTAGE" : "0.40", 24 | "MAX_ZERO_DIST_PERCENTAGE" : "0.20", 25 | "MAX_ZERO_MAPQ0_PERCENTAGE" : "0.20", 26 | "MAX_UNMAPPED_PERCENTAGE" : "0.10" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /collateral/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: Arial, Helvetica, sans-serif; 3 | font-size: 10px; 4 | -webkit-text-size-adjust:100%; 5 | -ms-text-size-adjust:100% 6 | } 7 | 8 | body { 9 | margin:0; 10 | } 11 | 12 | h1, 13 | .h1 { 14 | font-size: 24px; 15 | } 16 | 17 | h2, 18 | .h2 { 19 | font-size: 20px; 20 | } 21 | 22 | h3, h4, h5, h6, p { 23 | text-align: left; 24 | margin-left: 30px; 25 | margin-right: 30px; 26 | } 27 | 28 | h3 { 29 | font-size: 16px; 30 | } 31 | 32 | h4 { 33 | font-size: 14px; 34 | } 35 | 36 | h5 { 37 | font-size: 12px; 38 | } 39 | 40 | h6 { 41 | font-size: 11px; 42 | } 43 | 44 | p { 45 | font-size: 14px; 46 | } 47 | 48 | block_img { 49 | float: right; 50 | clear: left; 51 | } 52 | 53 | tr:nth-child(even) { 54 | background-color: #DDDDDD; 55 | } 56 | .small { 57 | font-size: 9px; 58 | } 59 | 60 | .left { 61 | text-align: left; 62 | } 63 | 64 | .right { 65 | text-align: right; 66 | } 67 | 68 | .center { 69 | display: block; 70 | margin-left: auto; 71 | margin-right: auto; 72 | } 73 | 74 | .centered { 75 | text-align: center; 76 | } 77 | 78 | .pass, .fail, .low-signal, .mixed-results { 79 | padding: 1px 6px; 80 | font-weight: bold; 81 | color: black; 82 | } 83 | 84 | .pass { 85 | background-color: #AAFFAA; 86 | } 87 | 88 | .fail { 89 | background-color: #FFAAAA; 90 | } 91 | 92 | .low-signal, .mixed-results { 93 | background-color: #FFDD77; 94 | } 95 | 96 | .pagebreak { page-break-before: always; } 97 | -------------------------------------------------------------------------------- /env.yml: -------------------------------------------------------------------------------- 1 | name: hic_qc 2 | channels: 3 | - bioconda 4 | - conda-forge 5 | dependencies: 6 | - _libgcc_mutex=0.1 7 | - _openmp_mutex=4.5 8 | - alsa-lib=1.2.13 9 | - brotli=1.1.0 10 | - brotli-bin=1.1.0 11 | - bzip2=1.0.8 12 | - c-ares=1.34.4 13 | - ca-certificates=2024.12.14 14 | - cairo=1.18.2 15 | - certifi=2024.8.30 16 | - contourpy=1.3.1 17 | - cycler=0.12.1 18 | - cyrus-sasl=2.1.27 19 | - dbus=1.13.6 20 | - double-conversion=3.3.0 21 | - expat=2.6.4 22 | - font-ttf-dejavu-sans-mono=2.37 23 | - font-ttf-inconsolata=3.000 24 | - font-ttf-source-code-pro=2.038 25 | - font-ttf-ubuntu=0.83 26 | - fontconfig=2.15.0 27 | - fonts-conda-ecosystem=1 28 | - fonts-conda-forge=1 29 | - fonttools=4.55.3 30 | - freetype=2.12.1 31 | - graphite2=1.3.13 32 | - harfbuzz=9.0.0 33 | - icu=75.1 34 | - importlib-metadata=8.5.0 35 | - keyutils=1.6.1 36 | - kiwisolver=1.4.7 37 | - krb5=1.21.3 38 | - lcms2=2.16 39 | - ld_impl_linux-64=2.43 40 | - lerc=4.0.0 41 | - libblas=3.9.0 42 | - libbrotlicommon=1.1.0 43 | - libbrotlidec=1.1.0 44 | - libbrotlienc=1.1.0 45 | - libcblas=3.9.0 46 | - libclang-cpp19.1=19.1.5 47 | - libclang13=19.1.5 48 | - libcups=2.3.3 49 | - libcurl=8.11.1 50 | - libdeflate=1.22 51 | - libdrm=2.4.124 52 | - libedit=3.1.20191231 53 | - libegl=1.7.0 54 | - libev=4.33 55 | - libexpat=2.6.4 56 | - libffi=3.4.2 57 | - libgcc=14.2.0 58 | - libgcc-ng=14.2.0 59 | - libgfortran=14.2.0 60 | - libgfortran5=14.2.0 61 | - libgl=1.7.0 62 | - libglib=2.82.2 63 | - libglvnd=1.7.0 64 | - libglx=1.7.0 65 | - libgomp=14.2.0 66 | - libiconv=1.17 67 | - libjpeg-turbo=3.0.0 68 | - liblapack=3.9.0 69 | - libllvm19=19.1.5 70 | - liblzma=5.6.3 71 | - libnghttp2=1.64.0 72 | - libnsl=2.0.1 73 | - libntlm=1.4 74 | - libopenblas=0.3.28 75 | - libopengl=1.7.0 76 | - libpciaccess=0.18 77 | - libpng=1.6.44 78 | - libpq=17.2 79 | - libsqlite=3.47.2 80 | - libssh2=1.11.1 81 | - libstdcxx=14.2.0 82 | - libstdcxx-ng=14.2.0 83 | - libtiff=4.7.0 84 | - libuuid=2.38.1 85 | - libwebp-base=1.4.0 86 | - libxcb=1.17.0 87 | - libxcrypt=4.4.36 88 | - libxkbcommon=1.7.0 89 | - libxml2=2.13.5 90 | - libxslt=1.1.39 91 | - libzlib=1.3.1 92 | - markdown=3.6 93 | - matplotlib=3.9.4 94 | - matplotlib-base=3.9.4 95 | - munkres=1.1.4 96 | - mysql-common=9.0.1 97 | - mysql-libs=9.0.1 98 | - ncurses=6.5 99 | - numpy=2.2.0 100 | - openjpeg=2.5.3 101 | - openldap=2.6.9 102 | - openssl=3.4.0 103 | - packaging=24.2 104 | - pcre2=10.44 105 | - pillow=11.0.0 106 | - pip=24.3.1 107 | - pixman=0.44.2 108 | - pthread-stubs=0.4 109 | - pyparsing=3.2.0 110 | - pysam=0.22.1 111 | - pyside6=6.8.1 112 | - python=3.12.8 113 | - python-dateutil=2.9.0.post0 114 | - python-pdfkit=1.0.0 115 | - python_abi=3.12 116 | - qhull=2020.2 117 | - qt6-main=6.8.1 118 | - readline=8.2 119 | - scipy=1.14.1 120 | - setuptools=75.6.0 121 | - six=1.17.0 122 | - tk=8.6.13 123 | - tornado=6.4.2 124 | - tzdata=2024b 125 | - unicodedata2=15.1.0 126 | - wayland=1.23.1 127 | - wheel=0.45.1 128 | - wkhtmltopdf=0.12.4 129 | - xcb-util=0.4.1 130 | - xcb-util-cursor=0.1.5 131 | - xcb-util-image=0.4.0 132 | - xcb-util-keysyms=0.4.1 133 | - xcb-util-renderutil=0.3.10 134 | - xcb-util-wm=0.4.2 135 | - xkeyboard-config=2.43 136 | - xorg-libice=1.1.2 137 | - xorg-libsm=1.2.5 138 | - xorg-libx11=1.8.10 139 | - xorg-libxau=1.0.12 140 | - xorg-libxcomposite=0.4.6 141 | - xorg-libxcursor=1.2.3 142 | - xorg-libxdamage=1.1.6 143 | - xorg-libxdmcp=1.1.5 144 | - xorg-libxext=1.3.6 145 | - xorg-libxfixes=6.0.1 146 | - xorg-libxi=1.8.2 147 | - xorg-libxrandr=1.5.4 148 | - xorg-libxrender=0.9.12 149 | - xorg-libxtst=1.2.5 150 | - xorg-libxxf86vm=1.1.6 151 | - zipp=3.21.0 152 | - zstd=1.5.6 153 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | CHANGES 2 | ======= 3 | 4 | * Handle cases where there are too few reads. (#24) 5 | * Update Readme.md (#23) 6 | * Collect additional mapping stats and output to separate table (#22) 7 | * Library Sufficiency and Report update (#21) 8 | * Update HQ RP >10kbp threshold based on review comments 9 | * Adjust QC thresholds to reflect empirical data and add an additional QC metric for intercontig HQ RPs spanning contigs >10kbp 10 | * Add pbr versioning (#18) 11 | * Switch to bam name in dup saturation plot 12 | * Removed git merge info from file 13 | * Merging from master 14 | * Added stats for high quality read pairs and made numerous aesthetic improvements 15 | * Class-based refactor (#15) 16 | * Added additional documentation, added outfile\_prefix to paths dict, changed histogram plotting routine to remove warning 17 | * Added additional documentation 18 | * Pulled Assembly stats into separate table, fixed some whitespace, switched fraction/proportion references to percentages 19 | * Set extrapolated dup rate to -1 if it fails, catch ZeroDivisionError, change fraction/proportion references to percentages 20 | * Incorporated changes from pretty\_report\_numbers branch including updates to report template md and css files 21 | * This is a class-based refactoring of bam\_to\_mate\_hist. It includes a number of additional features including: - Detection of coordinate-sorted bam files (if labeled in header) - Skipping of supplementary and secondary reads - Counting of unmapped reads 22 | * Add Travis CI integration (#13) 23 | * Switch badge to be based off of master branch 24 | * Add Travis CI badge 25 | * Added missing scipy dependency 26 | * Fixing travis file (again) 27 | * Fixing travis file 28 | * Initial commit for setup.py 29 | * Initial commit for Travis CI 30 | * Minor indentation fix 31 | * Fixed issue with zero dist reads in log log plot 32 | * Added log-log plot, use basename for bamfile in histograms 33 | * Add default returns for V and K when exiting dupe saturation early 34 | * Add writing out of dists file, containing all distances in the histogram 35 | * Added V and K from dup saturation curve fitting to output tsv 36 | * Skip unneeded metadata 37 | * Fix leftover template call 38 | * Replace explicit dictionary printing 39 | * Updated README to reflect python3 support and suggest installation using conda 40 | * Added python 3 compatibility 41 | * updated requirements to give proper pysam version 42 | * Fixed documentation for make\_histograms 43 | * Fixed parse\_bam\_file doc line 44 | * Added line for Fraction of read pairs >10KB apart mapping to contigs >10Kbp 45 | * Added stats for proportion of reads mapping to contigs >10Kbp with >10Kbp insert size. Also added -1 option to parse all reads in bam file 46 | * Added test cases for num 10Kbp reads, num reads mapping to 10Kbp contigs 47 | * Updated tests to account for change to count dict, updated documentation in bam\_to\_mate\_hist.py 48 | * Switched from list to dict for isize to reduce memory usage 49 | * fixed a few bugs and edge cases arising from duplicate saturation curve estimation for the report. changed how reports are versioned as it was messing up HTML conversion. fixed some test cases 50 | * Additional merge. Added extra dup stats to tsv 51 | * Additional merge 52 | * Merged changes from duplicate plotting branch 53 | * fixing some stuff raised in review 54 | * Added duplication curve plotting 55 | * Added duplicate saturation curve plotting 56 | * added a pass/fail row to the table, along with logic to populate it based on stats 57 | * updates to readme to explain changes. added setup script to enable report version tracking. updates to report template to allow version tracking 58 | * some docstring changes 59 | * missed committing the testing changes, here they are 60 | * added mapq zero counts, fixed tests so they don't fail with refactoring changes, fixed md template to give all data 61 | * fixed pairs vs reads correction 62 | * adding some features requested to report, specifically assembly stats. along the way refactoring code to avoid extremely cumbersome methods 63 | * added \_\_init\_\_ file 64 | * added unit tests, collateral for tests, and fixed a couple of bugs emerging in testing 65 | * removed recommended read numbers as potentially confusing, fixed split read counting 66 | * fixed a histogram+num reads counting bug 67 | * fixed zero-distance counting issue 68 | * added support for num reads desired total, basic 69 | * last context manager add 70 | * response to code review 71 | * adding a little more information about duplicates in reporting 72 | * Added some info to template boilerplate. Also fixed duplicate counting bug in script 73 | * fixed the sam flag check for dupes (i think) 74 | * added duplicate read support. also added code to compute assembly n50s, but not currently used 75 | * cleaned up script a bit, packaged all of the stats handling and printing into a function to de-clutter \_\_main\_\_ 76 | * update readme for qc reports 77 | * fixed plot path for embedding in report, a couple of minor report things 78 | * fixed CLI for making reports option 79 | * report now working, not beautiful. messed around with style etc. a lot 80 | * report now working, not beautiful. messed around with style etc. a lotwq 81 | * trying out making a pdf report. not quite working yet, had to take on a bunch of dependencies like wkhtmltopdf which i don't love, need to figure them out 82 | * added a few additional details to readme 83 | * added option to specify outfile path 84 | * Update Readme.md 85 | * added split read counting as a tracked heuristic of Hi-C lib QC 86 | * Updated readme to reflect split read reporting 87 | * added split read counting as a tracked heuristic of Hi-C lib QC 88 | * updated readme, added some examples and collateral dir 89 | * added functionality to do internal ABC QC, fixed minor bug in counting total number of reads 90 | * added functionality to do internal ABC QC, fixed minor bug in counting total number of reads 91 | * fixed y-axes to extend (almost) to zero on the bottom, and to print out more informative info on Hi-C lib quality 92 | * updated readme with interpretations 93 | * added counting of zero-distance mates as diagnostic to script 94 | * fixed matplotlib on ubuntu via ssh 95 | * updated readme to reflect clone/install command 96 | * added requirements file to ease installation 97 | * cleaned readme a little bit more 98 | * changed readme clone instructions to be accurate 99 | * initial commit 100 | * Initial commit 101 | -------------------------------------------------------------------------------- /tests/collateral/input/abc_test.empty.bam.bai: -------------------------------------------------------------------------------- 1 | BAI -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.com/phasegenomics/hic_qc.svg?branch=master)](https://travis-ci.com/phasegenomics/hic_qc) 2 | 3 | # `hic_qc.py` readme. 4 | 5 | This script is intended as a simple QC method for Hi-C libraries, based on reads in a BAM file aligned to some genome/assembly. For our full recommendations on aligning and QCing Hi-C data, please [see here](https://phasegenomics.github.io/2019/09/19/hic-alignment-and-qc.html). 6 | 7 | The most informative Hi-C reads are the ones that are long-distance contacts, or contacts between contigs of an assembly. This tool quantifies such contacts and makes plots of contact distance distributions. The most successful Hi-C libraries have many long-distance and among-contig contacts. 8 | 9 | Hi-C connectivity drops off in approximately a power-law with increasing linear sequence distance. Consequently, one expects Hi-C reads to follow a characteristic distribution, wherein there is a spike of many read pairs at distances close to zero, which drops off smoothly (in log space) with increasing distance. If there are odd spikes or discontinuities, or if there are few long-distance contacts, there may be a problem either with the library or the assembly. 10 | 11 | ## Dependencies 12 | * python 13 | * numpy 14 | * pysam 15 | * matplotlib 16 | * pdfkit 17 | * markdown 18 | * wkhtmltopdf (needs to be installed manually) 19 | 20 | ## Installation 21 | 22 | ### Conda installation 23 | To install using conda, run the following commands in sequence (assumes you already have conda and git installed): 24 | ``` 25 | git clone https://github.com/phasegenomics/hic_qc.git 26 | cd hic_qc/ 27 | conda env create -n hic_qc --file env.minimal.yml 28 | conda activate hic_qc 29 | pip install --no-deps -e . 30 | ``` 31 | 32 | You may need to run a `conda init` command to set up your shell if you haven't previously initialized conda in your shell. 33 | 34 | ## Usage 35 | In the most basic use-case, you can run the script in a terminal 36 | 37 | `python hic_qc.py -b input.bam -n num_reads_to_use -r` 38 | 39 | where `input.bam` is your BAM file from aligning Hi-C reads to your reference, and `num_reads_to_use` is just the number of read pairs you want to sample from the BAM file (default 1 million read pairs; assuming there are this many reads in the file). 40 | 41 | The script will write plots in PDF format to the file `Read_mate_dist.pdf` in the working directory, unless `-o` or `--outfile` are set as described below. 42 | 43 | The script will also quantify some basic QC metrics and print those to the screen. 44 | 45 | The script can also make a full-on PDF report of those metrics with the plots embedded if you set the `-r`/`--make_report` flag. 46 | 47 | To set the name of the files written out, such as the PNG figures and the report PDF, set the `-o /path/to/outfile` or `--outfile_name /path/to/outfile` parameters. 48 | 49 | QC is performed using a set of thresholds in JSON format. By default, the file `hic_qc/collateral/thresholds.json` is used. The chosen file may be changed with the `--thresholds` flag. Note that the thresholds in the default file are informed by Phase Genomics' analysis of thousands of Hi-C libraries, and reflect what we ourselves use for QC. 50 | 51 | Different QC thresholds may be present in a thresholds file. The default file includes thresholds for genome scaffolding projects and metagenome deconvolution projects. The `--sample_type` argument is used to specify which set of thresholds in the thresholds file should be used in the run, and is also noted at the top of the report. By default, the `genome` sample type is used. Additional sample types may be added to a thresholds JSON file by making them keys in the file. 52 | 53 | ## Library judgement and thresholds 54 | 55 | ### Judgement categories 56 | The report includes a judgement about the library and the assembly it was mapped to based on the observed statistics, shown at the top of the report. Libraries are given one of four classifications: 57 | 58 | * **SUFFICIENT** - the library and assembly appear to be sufficient for the purposes shown in the report. 59 | * **INSUFFICIENT** - the library and assembly appear to be insufficient for the purposes shown in the report. 60 | * **MIXED RESULTS** - the library and assembly are probably sufficient for the purposes shown in the report, but there is some additional noise or other unexpected properties in the report as well. 61 | * **LOW SIGNAL** - the library and assembly don't appear to be actively bad, but there is not very much observable long-range Hi-C signal. It's likely they are insufficient for the purposes shown in the report. 62 | 63 | IMPORTANT NOTE: because input assembly is a significant contributor to the ability to perform a given analysis, a good library can still generate a failed result with a bad assembly. This can particularly occur with difficult-to-align-to assemblies, such as polyploids or highly heterozygous/repetitive assemblies. 64 | 65 | ### "Good" properties 66 | Three statistics are used to determine if a set of alignments has "good" aspects to it: 67 | 68 | * **HQ RPs >10KB apart (CTGs >10KB)**: the percentage of read pairs that map with high quality (MAPQ >=20, max edit distance <=5, not dupes) in which both mates align to the same contig, the contig is at least 10kbp long, and the mates are at least 10kbp apart. 69 | * **Intercontig HQ RPs (CTGs >10KB)**: the percentage of read pairs that map with high quality in which each mates aligns to a different contig, and each of those contigs are at least 10kbp. 70 | * **Same strand HQ RPs**: the percentage of read pairs that map with high quality to the same strand (such reads are almost guaranteed to be Hi-C junctions). 71 | 72 | The entire set of alignments is deemed to have "good" properties if ALL THREE good criteria pass the threshold. 73 | 74 | ### "Bad" properties 75 | Three statistics are used to determine if a set of alignments has "bad" aspects to it: 76 | * **Duplicate reads**: the percentage of reads that are flagged as PCR duplicates (by a prior tool such as Picard or SAMBLASTER). 77 | * **Zero map quality reads**: the percentage of reads aligning with zero MAPQ. 78 | * **Unmapped reads**: the percentage of reads that could not be mapped. 79 | The entire set of alignments is deemed to have "bad" properties if ANY OF THE THREE bad criteria fail the threshold. 80 | 81 | ### Generating the final judgement 82 | Thresholds for these "good" and "bad" aspects come from the specified thresholds JSON file and are shown in the report. The fields in the report are highlighted for convenience to show whether a specific metric passed or failed the threshold. These are used to generate the judgement calls: 83 | * **SUFFICIENT** - "good" and "not bad" 84 | * **INSUFFICIENT** - "not good" and "bad" 85 | * **MIXED RESULTS** - "good" and "bad" 86 | * **LOW SIGNAL** - "not good" and "not bad" 87 | 88 | ## Histogram plot characteristics to look for 89 | Histogram plots should show some characteristic features: 90 | 91 | * Substantial long-range contacts (note that contact distance is bounded by the assembly). You will want to see at least some contacts approximately as long as your longest contig. In the log-log histogram, the appearance of a second hump or positive slope after the initial dropoff is a very good qualitative sign. 92 | * Gradual drop-off in signal with increasing distance (in log space). Choppiness or spikes in the distribution may indicate problems such as collapsed repeats or chimerisms, unless it can be attributed to sampling error due to (very) small numbers of reads. Periodicity in the distribution with distance often indicates problems. 93 | * The leftmost spike of mates mapping very close is always the most prominent feature in the plot. However, it should not be too much larger than the rest of the distribution, or you are not having enough long-distance contacts. A dropoff of 3-4 orders of magnitude in the 0-20KB plot is the most you want to see in that sudden dropoff. Ideally it would be only 1-2 orders of magnitude dropoff in the 0-20KB range. 94 | 95 | ## Example histograms 96 | The collateral folder includes several histograms which serve as examples of what is expected for a good Hi-C library. 97 | 98 | ## Statistics reported 99 | * Number of read pairs with mates mapping to exactly the same position (distance == 0). These are bad. We observe these reads at some rate all the time, but they are especially abundant when there is a problem. This proportion should be small, no more than 10% and ideally much smaller. That said, if other measures look ok it might be worth trying a library even if there are many distance == 0 pairs. 100 | * Number of read pairs with mates mapping >10KB apart. These are good. We would ideally like to see lots of very long-distance contacts between mates, as that is a sign of strong Hi-C signal. On the order of 1-20% is reasonable, though it depends on the assembly. For scaffolding best results are obtained when this is higher than 5%. 101 | * Number of read pairs with mates mapping to different contigs/chromosomes. These are good if they represent contacts within a cell, but bad if they represent noise or contacts between cells (e.g. for metagenomic data). On the order of 10-40% seems standard, again it depends on particulars of the assembly. 102 | * Number of split reads. These are good, usually, as they hopefully represent Hi-C junctions and thus successful Hi-C. There are of course other reasons why a read might be split. 103 | 104 | ## What do I do if there is a problem? 105 | Problems observed in QC may indicate an issue either with the Hi-C reads or the assembly used for alignments. If the assembly is bad or e.g. comes from a distantly related organism or set of organisms, you should expect to see artifacts in the alignment of Hi-C reads. 106 | 107 | * If the issue is the reads, you can try filtering your read alignments, either removing bad contigs or low-confidence reads. Our tool `matlock` has utilities for doing this. 108 | * If the issue is the assembly, you can either get a new/more appropriate assembly somehow, or you can attempt to fix your existing assembly. 109 | * The best way to fix assemblies in our experience is to break up chimerically assembled contigs. This can be achieved by either breaking on gaps if they exist in your assembly (e.g. runs of Ns) under the assumption that most chimerae span such gaps, or by directly inferring and breaking misjoins in your assembly. Breaking on gaps is fairly trivial, and our tool `polar_star` can help you infer and break misjoins using long read data. 110 | * If the issue is that you simply don't have enough long-distance Hi-C contacts, **unavoidably you will sometimes have to remake the Hi-C library**. 111 | -------------------------------------------------------------------------------- /collateral/HiC_QC_report_template.md: -------------------------------------------------------------------------------- 1 |
2 | Phase Genomics logo 3 | 4 | # Hi-C Library QC Report 5 | 6 | ## Input Data 7 | 8 | | File Type                   | File Name                 | 9 | |:------------------| :--------------------| 10 | | BAM File | {bamname} | 11 | | Assembly File | {ref_assembly} | 12 | | Forward Hi-C Reads | {fwd_hic_reads} | 13 | | Reverse Hi-C Reads | {rev_hic_reads} | 14 | 15 | ## {qc_purpose} Sufficiency 16 | 17 | | Label | Library statistics | Expected values | 18 | | :----------- |:-----------------:| --------------------:| 19 | | Subjective Hi-C library judgment | {judgment} | See Judgment | 20 | | Same strand high-quality* (HQ) read pairs (RPs) | {same_strand_hq_html} | > {same_strand_threshold}% | 21 | | Informative RPs** | {informative_read_pairs_html} | > {informative_read_pairs_threshold}% | 22 | 23 |
24 |
25 | *High-quality (HQ) read pairs have minimum mapping quality >= 20, maximum edit distance <= 5, and are not duplicates.
26 | **Informative read pairs are read pairs which have MAPQ > 0, are not PCR duplicates, and map to different contigs or >10kb apart. 27 | 28 |
29 | 30 | ## Metrics Demonstrating Strong Proximity Signal 31 | 32 | | Label | Library statistics | Expected values | 33 | | :----------- |:-----------------:| --------------------:| 34 | | Fraction of HQ RPs >10kb apart (CTGs >10kb)* | {long_contacts_html} | > {long_contacts_threshold}% | 35 | | Fraction of HQ RPs Intercontig (CTGs >10kb)** | {intercontig_hq_contacts_html} | > {intercontig_hq_contacts_threshold}% | 36 | | Informative HQ RPs per-contig per-1M-RPs (CTGs >5kb)*** | {usable_hq_gt_5k_per_million_html} | > {min_usable_reads_per_contig_per_million_threshold} | 37 | 38 |
39 |
40 | *The proportion of read pairs that span at least 10kb, out of all read pairs that map (a) with high-quality, (b) to the same contig, (c) where that contig is at least 10kb long.
41 | **The proportion of read pairs mapping to two different contigs each greater than 10kb, out of all read pairs that map with high-quality.
42 | ***The average number of HQ reads, per contig among contigs at least 5kb in length, per million read pairs, that are informative for identifying contigs which belong on the same chromosome.
43 |
44 | 45 | ## Noninformative Read Pair Breakdown 46 | 47 | | Label | Library statistics | Expected values | 48 | | :----------- |:-----------------:| --------------------:| 49 | | Noninformative RPs* | {noninformative_read_pairs_html} | <= {noninformative_read_pairs_threshold}% | 50 | | Duplicate reads | {high_dupe_html} | < {high_dupe_threshold}% | 51 | | Zero map distance read pairs | {many_zero_dist_pairs_html} | <= {many_zero_dist_threshold}% | 52 | | Zero MAPQ reads | {many_zero_mapq_reads_html} | <= {many_zero_mapq_threshold}% | 53 | | Unmapped reads | {many_unmapped_reads_html} | <= {many_unmapped_threshold}% | 54 | 55 |
56 |
57 | *Note that the sum of informative and noninformative read pairs is not 100% because read pairs with mapping distance between 1b and 10kb are not classified as either informative or noninformative.
58 | Because noninformative reads can belong to more than one category, these numbers may sum to a value larger than the overall noninformative read pair amount at the top of the report.
59 |
60 | 61 | 62 |
63 | 64 | ## Assembly Statistics 65 | 66 | | Label | Assembly statistics | 67 | |:-----------------------------|-------------------------:| 68 | | BAM file | {bamname} | 69 | | Forward Hi-C Reads | {fwd_hic_reads} | 70 | | Reverse Hi-C Reads | {rev_hic_reads} | 71 | | Assembly file | {ref_assembly} | 72 | | Assembly size | {total_length} | 73 | | Contig (CTG) N50 | {N50} | 74 | | CTGs | {contigs} | 75 | | CTGs > 10kb | {contigs_greater_10k} | 76 | | CTGs > 5kb | {contigs_greater_5k} | 77 | 78 | ## Extended Library Statistics 79 | 80 |
81 | 82 | | Label | Library statistics | Expected values | 83 | | :----------- | --------------------:| --------------------:| 84 | | Total read pairs (RPs) analyzed | {total_read_pairs} | N/A | 85 | | High-quality (HQ) RPs | {perc_hq_rp} | N/A | 86 | | Clustering usable HQ reads per contig (CTGs >5kb)* | {usable_hq_gt_5k_html} | > {usable_hq_gt_5k_threshold} | 87 | | RPs >10kb apart | {perc_pairs_greater_10k} | 1-15% | 88 | | RPs >10kb apart (CTGs >10kb) | {perc_pairs_greater_10k_on_contigs_greater_10k} | 1-15% | 89 | | Intercontig RPs | {perc_intercontig_pairs} | 10-60% (contigs) 1-20% (chromosomes) | 90 | | Intercontig HQ RPs | {perc_intercontig_pairs_hq} | 10-60% (contigs) 1-20% (chromosomes) | 91 | | Same strand RPs | {perc_pairs_on_same_strand} | 2-50% | 92 | | Split reads | {perc_split_reads} | 1-10% (PG libraries) 30%+ (other libraries) | 93 | | Alignment Parameters | {alignment_command_line} | N/A 94 | | Samblaster Parameters | {samblaster} | N/A 95 | | Restriction Enzyme(s) | {lib_enzyme} | N/A 96 |
97 | 98 |
99 |
100 | *The average number of usable high-quality read pairs per contig, for contigs greater than 5kb. Read pairs are "usable" if they map (a) with high-quality, (b) to different contigs, (c) where each of those contigs are greater than 5kb and (d) both mappings are high-quality.
101 |
102 | 103 |
104 | 105 | ## Aligned mate distance histograms 106 | 107 | !["Long range interaction histogram"]({long_hist}) 108 | !["Short range interaction histogram"]({short_hist}) 109 | 110 | !["Log-log interaction histogram (counts)"]({log_log_hist}) 111 | !["Log-log interaction histogram (density)"]({log_log_norm_hist}) 112 | 113 |
114 | ## Alignment distance statistics and plots 115 | We briefly describe some of the statistics we compute below to aid interpretation of this report. 116 | 117 | ### Subjective Hi-C Library Judgment 118 | While Hi-C data is nuanced and some analyses are more sensitive to data quality than others, a basic quality assessment can usually be made by examining the mapping characteristics of the Hi-C library. Based on our experience working with Hi-C data, we classify libraries into one of four QC categories: 119 | - **Sufficient** means that from everything we can tell, the library looks to be in great shape. Proceed to full sequencing or analysis with confidence. 120 | - **Mixed Results** means that the library is good in some ways, but not in others. Perhaps it has a good amount of long-range data, but there are also an elevated number of read pairs with MAPQ 0. Usually, data generated from Mixed Results libraries works out just fine (a high MAPQ 0 number can be due to repetitiveness in the assembly or unpurged haplotigs, for example), but it is good to know there may have been a few hiccups in the library prep in case troubleshooting is needed down the line. 121 | - **Low Signal** means that the library contains good Hi-C signal, but it's in lower percentage than usual. These libraries are generally good for generating useful Hi-C data, but you may need to sequence a little deeper than normal to get enough of it. You might consider size selecting the library to discard reads outside the 300-700bp range, as these are unlikely to be good Hi-C junctions. Alternatively, you might just want to prep a new library. 122 | - **Insufficient** means that the library, or perhaps the library in combination with a low-contiguity or error-prone assembly, does not look useful. Sometimes size selection can rescue such libraries, but sometimes a new prep is the only way forward.

[Contact us](mailto:support@phasegenomics.com) if your library is not sufficient and we will help you out. 123 | 124 | ### Read pairs on same strand 125 | This is the percentage of reads mapping to the same contig in the same orientation (FF or RR). For shotgun libraries, this should be ~1%, but for a pure Hi-C library, it could be as high as 50%. This is a primary metric of Hi-C library quality because it is minimally affected by assembly contiguity. 126 | 127 | ### Read pairs > 10kb apart 128 | This is the percentage of read pairs which map to the same contig, with at least 10kb separating them. More is always better, but because this number is affected by assembly contiguity, there is not a specific target threshold. Note that for some analyses, such as scaffolding or metagenomic deconvolution, read pairs that map to the same contig are not useful because they do not provide information that the assembly doesn't already contain. This statistic is more useful for these projects because it correlates with library prep success. These reads are useful for analyses like structural variant analysis or assembly misjoin detection, because they provide detailed structural information about existing assembled sequences. 129 | 130 | ### Read pairs > 10kb apart mapping to contigs >10kb 131 | This is the percentage of read pairs which map to the same contig, with at least 10kb separating them, but only considering read pairs mapping to contigs that are at least 10kb long. This attempts to corrects for assembly contiguity differences. More is always better, but typically at least 5% is desired. Note that for some analyses, such as scaffolding or metagenomic deconvolution, read pairs that map to the same contig are not useful because they do not provide information that the assembly doesn't already contain. This statistic is more useful for these projects because it correlates with library prep success. These reads are useful for analyses like structural variant analysis or assembly misjoin detection, because they provide detailed structural information about existing assembled sequences. 132 | 133 | ### Read pairs mapping to different contigs or chromosomes 134 | This is the percentage of read pairs which map to different contigs, which is particularly important. More is always better, but because this number is affected by assembly quality, there is not a specific target threshold, although at least 20% on *de novo* assembly projects is helpful. These reads are the primary source of information for Hi-C scaffolding or metagenomic deconvolution analyses. This statistic useful on most *de novo* projects because it also correlates with library prep success. These reads may be useful for analyses like structural variant analysis or assembly misjoin detection if those are performed on lower contiguity assemblies, because they provide detailed structural information about sequences which were not assembled together into contigs. 135 | 136 | ### Split reads 137 | Traditionally, split reads have been a favored measure of Hi-C library quality because they directly exhibit Hi-C junctions. Most traditional Hi-C library preparations produce many reads that sequence through junctions because their Hi-C junctions tend to occur randomly on the proximity ligated chimeric molecules. However, Phase Genomics libraries, whether produced in our laboratory or by means of our Plant, Animal, Human, or Microbe Hi-C kits, will have a generally lower percentage of split reads. This is because we have optimized our Hi-C protocol to enrich for slightly longer fragments around Hi-C junctions, such that each read is less likely to read through a junction even when a junction is present. 138 | 139 | This innovation improves mappability and increases the amount of useful data and reduces the utility of split read measurements to assess library quality. We therefore rely more heavily on metrics that directly relate to the usefulness of Hi-C reads for proximity analysis, such as the percentage of read pairs that map to the same strand or to different contigs. 140 | 141 | ### Duplicate reads 142 | **IMPORTANT NOTE: THE DUPLICATE FLAG IS NOT SET BY DEFAULT IN A BAM FILE. YOU NEED TO EXPLICITLY SET IT BY E.G. RUNNING SAMBLASTER OR PICARD MARKDUPLICATES ON YOUR BAM FILE. IF THE PERCENT OF DUPLICATES IS EXACTLY ZERO, IT PROBABLY MEANS THAT THE FLAG HAS NOT BEEN SET.** 143 | 144 | Sequencing libraries frequently contain duplicate reads due to PCR or optical issues. These are generally considered to be non-informative because they are chemical artifacts rather than biological signal and are thus typically excluded from further analysis. Higher percentages of duplicate reads are also correlated with low library complexity and poor library performance, making the percentage of duplicate reads a useful quality control measure. 145 | 146 | ### Unmapped reads 147 | A high percent of unmapped reads may indicate sequence is missing from the reference, the reads are mapped to the wrong reference, or the sample is contaminated. 148 | 149 |
150 |

151 | REPORT VERSION: {version} 152 |

153 | -------------------------------------------------------------------------------- /tests/collateral/input/interleaved_header.bam.bai: -------------------------------------------------------------------------------- 1 | BAI 2 | -------------------------------------------------------------------------------- /tests/test_hic_qc.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python 2 | ''' 3 | Max Press 4 | August 22, 2018 5 | Phase Genomics 6 | 7 | hic_qc/test_hic_qc.py 8 | 9 | This file contains unit tests for functions of the hic_qc.py script. 10 | 11 | Copyright 2020, Phase Genomics Inc. All rights reserved. 12 | 13 | The contents of this file are proprietary and private and are not intended for 14 | distribution or use by any person or entity except Phase Genomics. You may not 15 | use, modify, or distribute it in any fashion. You may not copy this file. You 16 | may not describe the contents of this file to any other party. 17 | ''' 18 | 19 | from __future__ import print_function 20 | from __future__ import division 21 | 22 | import os 23 | import pathlib 24 | import shutil 25 | import sys 26 | import unittest 27 | import hic_qc 28 | import pysam 29 | 30 | try: 31 | FileNotFoundError 32 | except NameError: 33 | FileNotFoundError = IOError 34 | 35 | DIRNAME = os.path.dirname(__file__) 36 | COLLATERAL_DIR = DIRNAME + "/collateral/" 37 | INPUT_DIR = COLLATERAL_DIR + "input/" 38 | OUTPUT_DIR = COLLATERAL_DIR + "output/" 39 | OUTFILE_PREFIX = OUTPUT_DIR + "Read_mate_dist" 40 | BAMFILE = INPUT_DIR + "abc_test.bam" 41 | 42 | class MyTestCase(unittest.TestCase): 43 | @classmethod 44 | def setUpClass(self): 45 | 46 | if not os.path.exists(OUTPUT_DIR): 47 | os.makedirs(OUTPUT_DIR) 48 | 49 | num_reads = 1000 50 | 51 | self.regular_header = BAMFILE 52 | self.interleaved_header = INPUT_DIR + "interleaved_header.bam" 53 | 54 | count_diff_refname_stub = False 55 | 56 | QC = hic_qc.HiCQC(outfile_prefix=OUTFILE_PREFIX) 57 | QC.logger.setLevel("ERROR") 58 | QC.parse_bam(BAMFILE, max_read_pairs=num_reads) 59 | self.QC = QC 60 | self.stats = QC.stats 61 | # self.stat_dict, total_reads, num_dupes = hic_qc.parse_bam_file( 62 | # num_reads=num_reads, bamfile=bamfile, count_diff_refname_stub=count_diff_refname_stub) 63 | 64 | self.example_read = pysam.AlignedSegment() 65 | self.example_read.reference_start = 30 66 | self.example_read.query_name = 'read1' 67 | self.example_read.mapping_quality = 30 68 | self.example_read.query_sequence = "AAAAACAAAACAAAAT" 69 | self.example_read.query_qualities = [30] * 16 70 | self.example_read.cigarstring = '16M' 71 | self.example_read.set_tag("NM", 0) 72 | self.example_read.set_tag("MD", 100) 73 | self.example_read.set_tag("AS", 100) 74 | self.example_read.set_tag("XS", 0) 75 | 76 | def setUp(self): 77 | self.QCtmp = hic_qc.HiCQC(outfile_prefix=OUTFILE_PREFIX) 78 | self.QCtmp.allowed_dupe_percentage = 0.5 79 | 80 | # Default stats 81 | self.QCtmp.stats['total_reads'] = 4000 82 | self.QCtmp.stats['total_read_pairs'] = 2000 83 | self.QCtmp.stats['total_read_pairs_hq'] = 1000 84 | self.QCtmp.stats['pairs_intracontig_hq'] = 200 85 | self.QCtmp.stats['pairs_on_contigs_greater_10k_hq'] = 600 86 | # driving metrics 87 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 4 # 2% 88 | self.QCtmp.stats['proximo_usable_rp'] = 101 # 5.05% 89 | self.QCtmp.stats['informative_pairs'] = 101 # >5% 90 | self.QCtmp.stats['noninformative_read_pairs'] = 1000 # 50% 91 | # other good metrics 92 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 4 # 0.67% 93 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 5 # 0.5% 94 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 10 95 | # noninformative breakdown 96 | self.QCtmp.stats['duplicate_reads'] = 800 # 20% 97 | self.QCtmp.stats['zero_dist_pairs'] = 400 # 20% 98 | self.QCtmp.stats['unmapped_reads'] = 400 # 10% 99 | self.QCtmp.stats['mapq0_reads'] = 800 # 20% 100 | 101 | @classmethod 102 | def tearDownClass(self): 103 | shutil.rmtree(OUTPUT_DIR) 104 | 105 | # all manually measured in the BAM file... 106 | def test_count_diff_chr_pairs(self): 107 | self.assertEqual(self.stats['intercontig_pairs'], 5) 108 | 109 | def test_count_splits(self): 110 | self.assertEqual(self.stats['split_reads'], 6) 111 | 112 | def test_count_dupe_reads(self): 113 | self.assertEqual(self.stats['duplicate_reads'], 2) 114 | 115 | def test_refs_right(self): 116 | self.assertEqual(len(self.QC.refs), 1288) 117 | 118 | def test_greater_10k_contigs_right(self): 119 | self.assertEqual(len(self.QC.contigs_greater_10k), 229) 120 | 121 | def test_count_zero_dist_pairs(self): 122 | self.assertEqual(self.stats['zero_dist_pairs'], 38) 123 | 124 | def test_reads_spanning_up_to_1k(self): 125 | self.assertEqual(self.stats['reads_spanning_up_to_1k'], 101) 126 | 127 | def test_reads_spanning_1k_to_10k(self): 128 | self.assertEqual(self.stats['reads_spanning_1k_to_10k'], 1) 129 | 130 | def test_reads_spanning_10k_to_100k(self): 131 | self.assertEqual(self.stats['reads_spanning_10k_to_100k'], 1) 132 | 133 | def test_reads_spanning_100k_to_1000k(self): 134 | self.assertEqual(self.stats['reads_spanning_100k_to_1000k'], 2) 135 | 136 | def test_reads_spanning_greater_than_1000k(self): 137 | self.assertEqual(self.stats['reads_spanning_greater_than_1000k'], 1) 138 | 139 | def test_all_reads(self): 140 | self.assertEqual(self.stats['reads_spanning_greater_than_1000k'] + self.stats['reads_spanning_100k_to_1000k'] 141 | + self.stats['reads_spanning_10k_to_100k'] + self.stats['reads_spanning_1k_to_10k'] + 142 | self.stats['reads_spanning_up_to_1k'] + self.stats['intercontig_pairs'], self.stats[ 143 | 'total_reads'] / 2) 144 | 145 | def test_count_num_pairs(self): 146 | self.assertEqual(self.stats['total_read_pairs'], 111) 147 | 148 | def test_count_gt_10kbp(self): 149 | self.assertEqual(self.stats['pairs_greater_10k'], 4) 150 | 151 | def test_count_gt_10kbp_actual(self): 152 | self.assertEqual(self.stats['pairs_greater_10k_on_contigs_greater_10k'], 4) 153 | 154 | def test_count_gt_10kbp_possible(self): 155 | self.assertEqual(self.stats['pairs_on_contigs_greater_10k'], 69) 156 | 157 | def test_dists_right_len(self): 158 | self.assertEqual(sum(self.QC.dists.values()) + self.stats['intercontig_pairs'], self.stats['total_read_pairs']) 159 | 160 | def test_dists_right_num_zeros(self): 161 | num_zeros = self.QC.dists[0] 162 | self.assertEqual(num_zeros, self.stats['zero_dist_pairs']) 163 | 164 | def test_is_split_read_false(self): 165 | self.QCtmp.update_read_stats(self.example_read) 166 | self.assertEqual(self.QCtmp.stats['split_reads'], 0) 167 | 168 | def test_is_split_read_true(self): 169 | self.example_read.set_tag("SA", 1) 170 | 171 | self.QCtmp.update_read_stats(self.example_read) 172 | self.assertEqual(self.QCtmp.stats['split_reads'], 1) 173 | 174 | def test_extract_header_info(self): 175 | with pysam.AlignmentFile(self.regular_header) as bam_fh: 176 | self.QCtmp.extract_header_info(bam_fh.header) 177 | 178 | def test_extract_header_info_interleaved(self): 179 | with pysam.AlignmentFile(self.interleaved_header) as bam_fh: 180 | self.QCtmp.extract_header_info(bam_fh.header) 181 | 182 | def test_python_version(self): 183 | '''Confirms that PYTHON version in Travis CI env matches expectation''' 184 | if "PYTHON" in os.environ: 185 | expected_python = os.environ["PYTHON"] if os.environ["PYTHON"] != "default" else "3.6" 186 | version_string = "{}.{}".format(*sys.version_info) 187 | self.assertEqual(version_string, expected_python) 188 | else: 189 | return True 190 | 191 | def test_plot_histograms(self): 192 | self.QC.plot_histograms() 193 | 194 | def test_pass_judgement_sufficient(self): 195 | '''should pass''' 196 | # major denominators 197 | # driving metrics 198 | self.QCtmp.stats['noninformative_read_pairs'] = 100 # 10% 199 | # other good metrics 200 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 400 # 66.7% 201 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 500 # 50% 202 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 1000 203 | # noninformative breakdown 204 | self.QCtmp.stats['duplicate_reads'] = 40 # 1% 205 | self.QCtmp.stats['zero_dist_pairs'] = 40 # 2% 206 | self.QCtmp.stats['unmapped_reads'] = 20 # 0.5% 207 | self.QCtmp.stats['mapq0_reads'] = 0 #0% 208 | self.QCtmp.pass_judgement() 209 | self.assertTrue(self.QCtmp.good_same_strand) 210 | self.assertTrue(self.QCtmp.good_informative_read_pairs) 211 | self.assertFalse(self.QCtmp.bad_noninformative_read_pairs) 212 | self.assertTrue(self.QCtmp.good_long_contacts) 213 | self.assertTrue(self.QCtmp.good_intercontig_contacts) 214 | self.assertTrue(self.QCtmp.good_usable_reads) 215 | self.assertFalse(self.QCtmp.high_dupe) 216 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 217 | self.assertFalse(self.QCtmp.many_unmapped_reads) 218 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 219 | self.assertTrue(self.QCtmp.judge_good) 220 | self.assertFalse(self.QCtmp.judge_bad) 221 | 222 | def test_pass_judgement_insufficient(self): 223 | '''should fail''' 224 | # major denominators 225 | # driving metrics 226 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 1 # 0.5% 227 | self.QCtmp.stats['proximo_usable_rp'] = 10 # 0.25% 228 | self.QCtmp.stats['informative_pairs'] = 100 # >5% 229 | self.QCtmp.stats['noninformative_read_pairs'] = 1500 # 75% 230 | # other good metrics 231 | # noninformative breakdown 232 | self.QCtmp.stats['duplicate_reads'] = 2000 # 50% 233 | self.QCtmp.stats['zero_dist_pairs'] = 1000 # 50% 234 | self.QCtmp.stats['unmapped_reads'] = 800 # 20% 235 | self.QCtmp.stats['mapq0_reads'] = 1200 # 30% 236 | self.QCtmp.pass_judgement() 237 | self.assertFalse(self.QCtmp.good_same_strand) 238 | self.assertFalse(self.QCtmp.good_informative_read_pairs) 239 | self.assertTrue(self.QCtmp.bad_noninformative_read_pairs) 240 | self.assertFalse(self.QCtmp.good_long_contacts) 241 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 242 | self.assertFalse(self.QCtmp.good_usable_reads) 243 | self.assertTrue(self.QCtmp.high_dupe) 244 | self.assertTrue(self.QCtmp.many_zero_dist_pairs) 245 | self.assertTrue(self.QCtmp.many_unmapped_reads) 246 | self.assertTrue(self.QCtmp.many_mapq_zero_reads) 247 | self.assertFalse(self.QCtmp.judge_good) 248 | self.assertTrue(self.QCtmp.judge_bad) 249 | 250 | def test_pass_judgement_mixed(self): 251 | # should be mixed results 252 | # major denominators 253 | # driving metrics 254 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 100 # 50% 255 | self.QCtmp.stats['proximo_usable_rp'] = 500 # 25% 256 | self.QCtmp.stats['informative_pairs'] = 100 # 5% 257 | self.QCtmp.stats['noninformative_read_pairs'] = 1500 # 75% 258 | # other good metrics 259 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 400 # 66.7% 260 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 500 # 50% 261 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 1000 262 | # noninformative breakdown 263 | self.QCtmp.stats['duplicate_reads'] = 2000 # 50% 264 | self.QCtmp.stats['zero_dist_pairs'] = 1000 # 50% 265 | self.QCtmp.stats['unmapped_reads'] = 800 # 20% 266 | self.QCtmp.stats['mapq0_reads'] = 1200 # 30% 267 | self.QCtmp.pass_judgement() 268 | self.assertTrue(self.QCtmp.good_same_strand) 269 | self.assertFalse(self.QCtmp.good_informative_read_pairs) 270 | self.assertTrue(self.QCtmp.bad_noninformative_read_pairs) 271 | self.assertTrue(self.QCtmp.good_long_contacts) 272 | self.assertTrue(self.QCtmp.good_intercontig_contacts) 273 | self.assertTrue(self.QCtmp.good_usable_reads) 274 | self.assertTrue(self.QCtmp.high_dupe) 275 | self.assertTrue(self.QCtmp.many_zero_dist_pairs) 276 | self.assertTrue(self.QCtmp.many_unmapped_reads) 277 | self.assertTrue(self.QCtmp.many_mapq_zero_reads) 278 | self.assertTrue(self.QCtmp.judge_good) 279 | self.assertTrue(self.QCtmp.judge_bad) 280 | 281 | def test_pass_judgement_low_signal(self): 282 | # should low signal 283 | # major denominators 284 | # driving metrics 285 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 1 # 0.5% 286 | self.QCtmp.stats['proximo_usable_rp'] = 10 # 0.25% 287 | self.QCtmp.stats['informative_pairs'] = 101 # >5% 288 | self.QCtmp.stats['noninformative_read_pairs'] = 100 # 10% 289 | # other good metrics 290 | # noninformative breakdown 291 | self.QCtmp.stats['duplicate_reads'] = 40 # 1% 292 | self.QCtmp.stats['zero_dist_pairs'] = 40 # 2% 293 | self.QCtmp.stats['unmapped_reads'] = 20 # 0.5% 294 | self.QCtmp.stats['mapq0_reads'] = 0 #0% 295 | self.QCtmp.pass_judgement() 296 | self.assertFalse(self.QCtmp.good_same_strand) 297 | self.assertTrue(self.QCtmp.good_informative_read_pairs) 298 | self.assertFalse(self.QCtmp.bad_noninformative_read_pairs) 299 | self.assertFalse(self.QCtmp.good_long_contacts) 300 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 301 | self.assertFalse(self.QCtmp.good_usable_reads) 302 | self.assertFalse(self.QCtmp.high_dupe) 303 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 304 | self.assertFalse(self.QCtmp.many_unmapped_reads) 305 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 306 | self.assertFalse(self.QCtmp.judge_good) 307 | self.assertFalse(self.QCtmp.judge_bad) 308 | 309 | def test_pass_judgement_close_not_sufficient(self): 310 | # should barely not pass 311 | # major denominators 312 | # driving metrics 313 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 3 # 1.5% - exactly on the threshold fails 314 | self.QCtmp.stats['proximo_usable_rp'] = 500 # 25% 315 | self.QCtmp.stats['informative_pairs'] = 101 # >5% 316 | self.QCtmp.stats['noninformative_read_pairs'] = 100 # 10% 317 | # other good metrics 318 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 400 # 66.7% 319 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 500 # 50% 320 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 1000 321 | # noninformative breakdown 322 | self.QCtmp.stats['duplicate_reads'] = 40 # 1% 323 | self.QCtmp.stats['zero_dist_pairs'] = 40 # 2% 324 | self.QCtmp.stats['unmapped_reads'] = 20 # 0.5% 325 | self.QCtmp.stats['mapq0_reads'] = 0 #0% 326 | self.QCtmp.pass_judgement() 327 | self.assertFalse(self.QCtmp.good_same_strand) 328 | self.assertTrue(self.QCtmp.good_informative_read_pairs) 329 | self.assertFalse(self.QCtmp.bad_noninformative_read_pairs) 330 | self.assertTrue(self.QCtmp.good_long_contacts) 331 | self.assertTrue(self.QCtmp.good_intercontig_contacts) 332 | self.assertTrue(self.QCtmp.good_usable_reads) 333 | self.assertFalse(self.QCtmp.high_dupe) 334 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 335 | self.assertFalse(self.QCtmp.many_unmapped_reads) 336 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 337 | self.assertFalse(self.QCtmp.judge_good) 338 | self.assertFalse(self.QCtmp.judge_bad) 339 | 340 | def test_pass_judgement_close_still_insufficient(self): 341 | # should still be insufficient just over the line 342 | # major denominators 343 | # driving metrics 344 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 1 # 0.5% 345 | self.QCtmp.stats['proximo_usable_rp'] = 10 # 0.25% 346 | self.QCtmp.stats['informative_pairs'] = 100 # >5% 347 | self.QCtmp.stats['noninformative_read_pairs'] = 1001 # 50.05% 348 | # other good metrics 349 | # noninformative breakdown 350 | self.QCtmp.stats['duplicate_reads'] = 2000 # 50% 351 | self.QCtmp.stats['zero_dist_pairs'] = 1000 # 50% 352 | self.QCtmp.stats['unmapped_reads'] = 800 # 20% 353 | self.QCtmp.stats['mapq0_reads'] = 1200 # 30% 354 | self.QCtmp.pass_judgement() 355 | self.assertFalse(self.QCtmp.good_same_strand) 356 | self.assertFalse(self.QCtmp.good_informative_read_pairs) 357 | self.assertTrue(self.QCtmp.bad_noninformative_read_pairs) 358 | self.assertFalse(self.QCtmp.good_long_contacts) 359 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 360 | self.assertFalse(self.QCtmp.good_usable_reads) 361 | self.assertTrue(self.QCtmp.high_dupe) 362 | self.assertTrue(self.QCtmp.many_zero_dist_pairs) 363 | self.assertTrue(self.QCtmp.many_unmapped_reads) 364 | self.assertTrue(self.QCtmp.many_mapq_zero_reads) 365 | self.assertFalse(self.QCtmp.judge_good) 366 | self.assertTrue(self.QCtmp.judge_bad) 367 | 368 | def test_pass_judgement_on_boundaries_should_be_low_signal(self): 369 | # should be low signal 370 | # major denominators 371 | # driving metrics 372 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 3 # 1.5% 373 | self.QCtmp.stats['proximo_usable_rp'] = 100 # 5% 374 | # other good metrics 375 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 15 # 2.5% 376 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 25 # 2.5% 377 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 600 378 | # noninformative breakdown 379 | self.QCtmp.pass_judgement() 380 | self.assertFalse(self.QCtmp.good_same_strand) 381 | self.assertTrue(self.QCtmp.good_informative_read_pairs) 382 | self.assertFalse(self.QCtmp.bad_noninformative_read_pairs) 383 | self.assertFalse(self.QCtmp.good_long_contacts) 384 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 385 | self.assertFalse(self.QCtmp.good_usable_reads) 386 | self.assertFalse(self.QCtmp.high_dupe) 387 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 388 | self.assertFalse(self.QCtmp.many_unmapped_reads) 389 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 390 | self.assertFalse(self.QCtmp.judge_good) 391 | self.assertFalse(self.QCtmp.judge_bad) 392 | 393 | def test_pass_judgement_just_past_boundaries_should_be_mixed_results(self): 394 | # should be low signal 395 | # major denominators 396 | # driving metrics 397 | self.QCtmp.stats['informative_pairs'] = 100 # 5% 398 | self.QCtmp.stats['noninformative_read_pairs'] = 1001 # 50.05% 399 | # other good metrics 400 | self.QCtmp.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] = 19 # 3.17% 401 | self.QCtmp.stats['pairs_intercontig_hq_gt10kbp'] = 26 # 2.6% 402 | self.QCtmp.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 601 403 | # noninformative breakdown 404 | self.QCtmp.stats['duplicate_reads'] = 801 # 20.025% 405 | self.QCtmp.stats['zero_dist_pairs'] = 401 # 20.05% 406 | self.QCtmp.stats['unmapped_reads'] = 401 # 10.025% 407 | self.QCtmp.stats['mapq0_reads'] = 801 # 20.025% 408 | self.QCtmp.pass_judgement() 409 | self.assertTrue(self.QCtmp.good_same_strand) 410 | self.assertFalse(self.QCtmp.good_informative_read_pairs) 411 | self.assertTrue(self.QCtmp.bad_noninformative_read_pairs) 412 | self.assertTrue(self.QCtmp.good_long_contacts) 413 | self.assertTrue(self.QCtmp.good_intercontig_contacts) 414 | self.assertTrue(self.QCtmp.good_usable_reads) 415 | self.assertTrue(self.QCtmp.high_dupe) 416 | self.assertTrue(self.QCtmp.many_zero_dist_pairs) 417 | self.assertTrue(self.QCtmp.many_unmapped_reads) 418 | self.assertTrue(self.QCtmp.many_mapq_zero_reads) 419 | self.assertTrue(self.QCtmp.judge_good) 420 | self.assertTrue(self.QCtmp.judge_bad) 421 | 422 | def test_pass_judgement_just_across_sufficient_boundary(self): 423 | # should pass 424 | # major denominators 425 | # driving metrics 426 | # other good metrics 427 | # noninformative breakdown 428 | self.QCtmp.pass_judgement() 429 | self.assertTrue(self.QCtmp.good_same_strand) 430 | self.assertTrue(self.QCtmp.good_informative_read_pairs) 431 | self.assertFalse(self.QCtmp.bad_noninformative_read_pairs) 432 | self.assertFalse(self.QCtmp.good_long_contacts) 433 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 434 | self.assertFalse(self.QCtmp.good_usable_reads) 435 | self.assertFalse(self.QCtmp.high_dupe) 436 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 437 | self.assertFalse(self.QCtmp.many_unmapped_reads) 438 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 439 | self.assertTrue(self.QCtmp.judge_good) 440 | self.assertFalse(self.QCtmp.judge_bad) 441 | 442 | def test_pass_judgement_just_across_insufficient_boundary(self): 443 | # should pass 444 | # major denominators 445 | # driving metrics 446 | self.QCtmp.stats['pairs_on_same_strand_hq'] = 3 # 1.5% 447 | self.QCtmp.stats['proximo_usable_rp'] = 100 # 5% 448 | self.QCtmp.stats['informative_pairs'] = 100 # 5% 449 | self.QCtmp.stats['noninformative_read_pairs'] = 1001 # 50.05% 450 | # other good metrics 451 | # noninformative breakdown 452 | self.QCtmp.pass_judgement() 453 | self.assertFalse(self.QCtmp.good_same_strand) 454 | self.assertFalse(self.QCtmp.good_informative_read_pairs) 455 | self.assertTrue(self.QCtmp.bad_noninformative_read_pairs) 456 | self.assertFalse(self.QCtmp.good_long_contacts) 457 | self.assertFalse(self.QCtmp.good_intercontig_contacts) 458 | self.assertFalse(self.QCtmp.good_usable_reads) 459 | self.assertFalse(self.QCtmp.high_dupe) 460 | self.assertFalse(self.QCtmp.many_zero_dist_pairs) 461 | self.assertFalse(self.QCtmp.many_unmapped_reads) 462 | self.assertFalse(self.QCtmp.many_mapq_zero_reads) 463 | self.assertFalse(self.QCtmp.judge_good) 464 | self.assertTrue(self.QCtmp.judge_bad) 465 | 466 | def test_empty_bam(self): 467 | bamfile = INPUT_DIR + "abc_test.empty.bam" 468 | self.QCtmp.parse_bam(bamfile, max_read_pairs=1000) 469 | self.QCtmp.pass_judgement() 470 | self.QCtmp.html_from_judgement() 471 | self.QCtmp.plot_histograms() 472 | self.QCtmp.stringify_stats() 473 | self.QCtmp.log_stats() 474 | self.QCtmp.write_stat_table() 475 | self.QCtmp.write_dists_file() 476 | self.QCtmp.write_pdf_report(quiet=True) 477 | 478 | def test_bad_report_path(self): 479 | self.QCtmp.paths["script_dir"] = "/not/a/path" 480 | with self.assertRaises(FileNotFoundError): 481 | self.QCtmp.write_pdf_report(quiet=True) 482 | 483 | def test_mem2_bam_header(self): 484 | mem2_bam = INPUT_DIR + "abc_test.mem2.nosamblaster.bam" 485 | self.QCtmp.parse_bam(mem2_bam, max_read_pairs=1000) 486 | self.assertTrue(self.QCtmp.bwa_command.startswith('bwa-mem2')) 487 | 488 | def test_no_samblaster_header(self): 489 | mem2_bam = INPUT_DIR + "abc_test.mem2.nosamblaster.bam" 490 | self.QCtmp.parse_bam(mem2_bam, max_read_pairs=1000) 491 | self.assertEqual(self.QCtmp.samblaster, 'samblaster command not found') 492 | 493 | 494 | if __name__ == '__main__': 495 | unittest.main() 496 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /hic_qc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # takes a bam file and makes a histogram of distances between mate alignments to the 4 | # reference assembly 5 | # takes the first 1M read pairs by default 6 | 7 | ### USAGE: 8 | # python hic_qc.py -b -n -o 9 | # creates files in the working directory with relevant plots, also text files of statistics. 10 | # flip -r flag (assuming you have dependencies) to make a PDF report with everything together. 11 | 12 | import argparse 13 | from collections import Counter 14 | import filecmp 15 | import importlib.metadata 16 | import logging 17 | import markdown as md 18 | import os 19 | import re 20 | import sys 21 | 22 | import matplotlib 23 | import matplotlib.pyplot as plt 24 | import numpy as np 25 | import pdfkit 26 | import pysam 27 | from scipy import optimize 28 | 29 | 30 | matplotlib.use('Agg') 31 | HICQC_VERSION = importlib.metadata.version('hic_qc') 32 | 33 | #try: 34 | # FileNotFoundError 35 | #except NameError: 36 | # FileNotFoundError = IOError 37 | 38 | # default QC thresholds if there is no thresholds file 39 | DEFAULT_MIN_SAME_STRAND_HQ_PERCENTAGE = 0.015 40 | DEFAULT_MIN_INFORMATIVE_READ_PAIRS_PERCENTAGE = 0.05 41 | DEFAULT_MAX_NONINFORMATIVE_READ_PAIR_PERCENTAGE = 0.50 42 | DEFAULT_MIN_LONG_CONTACT_PERCENTAGE = 0.03 43 | DEFAULT_MIN_INTERCONTIG_CONTACT_PERCENTAGE = 0.025 44 | DEFAULT_MIN_USABLE_READS_PER_CONTIG = 600 45 | DEFAULT_MIN_USABLE_READS_PER_CONTIG_PER_MILLION = 100000 46 | DEFAULT_MAX_DUPE_PERCENTAGE = 0.40 47 | DEFAULT_MAX_ZERO_DIST_PERCENTAGE = 0.20 48 | DEFAULT_MAX_ZERO_MAPQ0_PERCENTAGE = 0.20 49 | DEFAULT_MAX_UNMAPPED_PERCENTAGE = 0.10 50 | 51 | def calc_nxx(header, xx=50): 52 | '''Calculate the NXX (typically N50) of an assembly given a pysam.AlignmentHeader object. 53 | 54 | Args: 55 | header (pysam.AlignmentHeader): the header from which to extract reference sequence lengths 56 | xx (float): the XX of NXX. we assume it is N50 so the default is 50. 57 | 58 | Returns: 59 | contig_len (int): the NXX (probably N50) of the assembly 60 | total (int): The total length of contigs in the assembly 61 | ''' 62 | 63 | frac = xx / 100.0 64 | lens = [contig['LN'] for contig in header['SQ']] 65 | lens.sort() 66 | total = sum(lens) 67 | nxx_len = total * frac 68 | 69 | cumsum = 0 70 | contig_len = 0 71 | for length in reversed(lens): 72 | contig_len = int(length) 73 | cumsum += length 74 | if cumsum >= nxx_len: 75 | break 76 | 77 | return contig_len, total 78 | 79 | class HiCQC(object): 80 | '''Class for extracting QC metrics from bam files and using them 81 | to create plots, print results, save tables, and create pdf reports. 82 | ''' 83 | 84 | def __init__(self, outfile_prefix='Read_mate_dist', sample_type='genome', thresholds_file=None, 85 | rp_stats=None, mq_stats=None, edist_stats=None, lib_enzyme=None): 86 | '''Initialize metrics for later extraction and conversion. 87 | ''' 88 | logging.basicConfig(format="[%(name)s - %(asctime)s] %(message)s", level=logging.INFO) 89 | self.logger = logging.getLogger("hic_qc") 90 | 91 | self.sample_type = sample_type.lower() 92 | self.qc_purpose = 'Unknown' 93 | self.lib_enzyme = lib_enzyme if lib_enzyme is not None else ['undefined'] 94 | self.ref_assembly = "reference assembly not found" 95 | self.fwd_hic_reads = "forward Hi-C reads not found" 96 | self.rev_hic_reads = "reverse Hi-C reads not found" 97 | 98 | if self.sample_type == 'metagenome': 99 | self.qc_purpose = 'Metagenome Deconvolution' 100 | elif self.sample_type == 'genome': 101 | self.qc_purpose = 'Genome Scaffolding' 102 | 103 | if thresholds_file is None: 104 | self.min_same_strand_hq_percentage = DEFAULT_MIN_SAME_STRAND_HQ_PERCENTAGE 105 | self.min_informative_read_pairs_percentage = DEFAULT_MIN_INFORMATIVE_READ_PAIRS_PERCENTAGE 106 | self.max_noninformative_read_pair_percentage = DEFAULT_MAX_NONINFORMATIVE_READ_PAIR_PERCENTAGE 107 | self.min_long_contact_percentage = DEFAULT_MIN_LONG_CONTACT_PERCENTAGE 108 | self.min_intercontig_contact_percentage = DEFAULT_MIN_INTERCONTIG_CONTACT_PERCENTAGE 109 | self.min_usable_reads_per_contig = DEFAULT_MIN_USABLE_READS_PER_CONTIG 110 | self.min_usable_reads_per_contig_per_million = DEFAULT_MIN_USABLE_READS_PER_CONTIG_PER_MILLION 111 | self.max_dupe_percentage = DEFAULT_MAX_DUPE_PERCENTAGE 112 | self.max_zero_dist_percentage = DEFAULT_MAX_ZERO_DIST_PERCENTAGE 113 | self.max_zero_mapq0_percentage = DEFAULT_MAX_ZERO_MAPQ0_PERCENTAGE 114 | self.max_unmapped_percentage = DEFAULT_MAX_UNMAPPED_PERCENTAGE 115 | else: 116 | import json 117 | with open(thresholds_file) as f: 118 | thresholds = json.load(f) 119 | self.min_same_strand_hq_percentage = float(thresholds[sample_type]['MIN_SAME_STRAND_HQ_PERCENTAGE']) 120 | self.min_informative_read_pairs_percentage = float(thresholds[sample_type]['MIN_INFORMATIVE_READ_PAIRS_PERCENTAGE']) 121 | self.max_noninformative_read_pair_percentage = float(thresholds[sample_type]['MAX_NONINFORMATIVE_READ_PAIR_PERCENTAGE']) 122 | self.min_long_contact_percentage = float(thresholds[sample_type]['MIN_LONG_CONTACT_PERCENTAGE']) 123 | self.min_intercontig_contact_percentage = float(thresholds[sample_type]['MIN_INTERCONTIG_CONTACT_PERCENTAGE']) 124 | self.min_usable_reads_per_contig = float(thresholds[sample_type]['MIN_USABLE_READS_PER_CONTIG']) 125 | self.min_usable_reads_per_contig_per_million = float(thresholds[sample_type]['MIN_USABLE_READS_PER_CONTIG_PER_MILLION']) 126 | self.max_dupe_percentage = float(thresholds[sample_type]['MAX_DUPE_PERCENTAGE']) 127 | self.max_zero_dist_percentage = float(thresholds[sample_type]['MAX_ZERO_DIST_PERCENTAGE']) 128 | self.max_zero_mapq0_percentage = float(thresholds[sample_type]['MAX_ZERO_MAPQ0_PERCENTAGE']) 129 | self.max_unmapped_percentage = float(thresholds[sample_type]['MAX_UNMAPPED_PERCENTAGE']) 130 | 131 | self.per_read_metrics = set(['duplicate_reads', 'mapq0_reads', 'split_reads', 'total_reads', 'unmapped_reads',]) 132 | self.per_pair_metrics = set(['different_ref_stub_pairs', 133 | 'informative_pairs', 134 | 'intercontig_pairs', 135 | 'intercontig_pairs_hq', 136 | 'pairs_greater_10k', 137 | 'pairs_greater_10k_on_contigs_greater_10k', 138 | 'pairs_intracontig_hq', 139 | 'pairs_intracontig_hq_gt10kbp', 140 | 'pairs_on_contigs_greater_10k', 141 | 'pairs_on_same_strand', 142 | 'pairs_on_same_strand_hq', 143 | 'proximo_usable_rp', 144 | 'proximo_usable_rp_hq', 145 | 'total_pairs_on_same_contig', 146 | 'total_read_pairs', 147 | 'total_read_pairs_hq', 148 | 'zero_dist_pairs', 149 | ]) 150 | # Dictionary of key --> numerator, denominator pairs for stringify_stats 151 | self.to_percents = { 152 | # Top Table 153 | 'perc_pairs_on_same_strand_hq': ('pairs_on_same_strand_hq', 'pairs_intracontig_hq'), 154 | 'perc_informative_read_pairs': ('informative_pairs', 'total_read_pairs'), 155 | # Other Good Metrics 156 | 'perc_pairs_intra_hq_gt10kbp': ('pairs_intracontig_hq_gt10kbp', 'pairs_intracontig_hq'), 157 | 'perc_intercontig_pairs_hq_gt10kbp': ('pairs_intercontig_hq_gt10kbp', 'total_read_pairs_hq'), 158 | # Usable reads number is in self.to_round 159 | # Noninformative Read Breakdown 160 | 'perc_noninformative_read_pairs': ('noninformative_read_pairs', 'total_read_pairs'), 161 | 'perc_duplicate_reads': ('duplicate_reads', 'total_reads'), 162 | 'perc_zero_dist_pairs': ('zero_dist_pairs', 'total_read_pairs'), 163 | 'perc_unmapped_reads': ('unmapped_reads', 'total_reads'), 164 | 'perc_mapq0_reads': ('mapq0_reads', 'total_reads'), 165 | # Extended Metrics 166 | 'perc_pairs_greater_10k': ('pairs_greater_10k', 'total_read_pairs'), 167 | 'perc_pairs_greater_10k_on_contigs_greater_10k': ('pairs_greater_10k_on_contigs_greater_10k', 'pairs_on_contigs_greater_10k'), 168 | 'perc_pairs_on_same_strand': ('pairs_on_same_strand', 'total_pairs_on_same_contig'), 169 | 'perc_intercontig_pairs': ('intercontig_pairs', 'total_read_pairs'), 170 | 'perc_intercontig_pairs_hq': ('intercontig_pairs_hq', 'total_read_pairs_hq'), 171 | 'perc_split_reads': ('split_reads', 'total_reads'), 172 | 'perc_hq_rp': ('total_read_pairs_hq', 'total_read_pairs'), 173 | 'perc_different_ref_stub_pairs': ('different_ref_stub_pairs', 'total_read_pairs') 174 | } 175 | self.to_round = set([ 176 | 'proximo_usable_rp_per_ctg_gt_5k', 177 | 'proximo_usable_rp_hq_per_ctg_gt_5k', 178 | 'proximo_usable_rp_hq_per_ctg_gt_5k_per_million' 179 | ]) 180 | 181 | self.convert_to_pairs = set(['unmapped_reads', 'split_reads', 'duplicate_reads', 'mapq0_reads']) 182 | 183 | self.paths = {'script_dir': os.path.dirname(__file__), 'outfile_prefix': outfile_prefix} 184 | self.paths['pg_logo'] = os.path.join(self.paths['script_dir'], 'collateral', 'PGBlueLogoHorSmall.png') 185 | 186 | self.N50 = None 187 | self.stats = Counter() 188 | self.dists = Counter() 189 | self.total_array = [] 190 | self.non_dup_array = [] 191 | 192 | if rp_stats is not None and mq_stats is not None and edist_stats is not None: 193 | rps = [] 194 | mqs = [] 195 | edists = [] 196 | self.mapping_dict = {} 197 | rp_stats = sorted(map(lambda x: int(1000 * x), rp_stats)) 198 | mq_stats = sorted(map(int, mq_stats)) 199 | edist_stats = list(reversed(sorted(map(int, edist_stats)))) 200 | 201 | for rp in rp_stats: 202 | self.mapping_dict[rp] = {} 203 | for mq in mq_stats: 204 | self.mapping_dict[rp][mq] = {} 205 | for ed in edist_stats: 206 | self.mapping_dict[rp][mq][ed] = 0 207 | self.rp_stats = rp_stats 208 | self.mq_stats = mq_stats 209 | self.edist_stats = edist_stats 210 | 211 | else: 212 | self.mapping_dict = None 213 | self.rp_array = None 214 | 215 | def parse_bam(self, bamfile, max_read_pairs=-1): 216 | '''Extract QC metrics from a specified bam file. It requires a read name sorted bam file. 217 | By default, it will parse all reads in the bam file, but a limit can be specified by max_read_pairs. 218 | This method performs read pairing. 219 | ''' 220 | 221 | if max_read_pairs != -1: 222 | self.logger.info('parsing the first {} read pairs in bam file {} '\ 223 | 'to QC Hi-C library quality'.format(max_read_pairs, bamfile)) 224 | else: 225 | self.logger.info('parsing all read pairs in bam file {} '\ 226 | 'to QC Hi-C library quality'.format(bamfile)) 227 | 228 | self.paths['bamfile'] = bamfile 229 | self.paths['bamname'] = os.path.basename(bamfile) 230 | 231 | a = None 232 | b = None 233 | i = 0 234 | 235 | with pysam.AlignmentFile(self.paths['bamfile']) as bam_fh: 236 | self.extract_header_info(bam_fh.header) 237 | 238 | for read in bam_fh: 239 | if read.is_secondary or read.is_supplementary: 240 | continue 241 | if a is None: 242 | a = read 243 | continue 244 | if max_read_pairs != -1 and i / 2 > max_read_pairs: 245 | break 246 | 247 | if read.query_name == a.query_name: 248 | b = read 249 | self.process_pair(a, b) 250 | a = None 251 | b = None 252 | else: 253 | a = read 254 | 255 | if i % 1000 == 0: 256 | self.update_dup_stats() 257 | i += 1 258 | 259 | self.finalize_stats() 260 | 261 | def extract_header_info(self, header, xx=50): 262 | '''Extract reference names, calculate N50, get total assembly length, and get set of contigs > 10kbp from a pysam header. 263 | Also checks if input bamfile is labeled as coordinate sorted and throws a ValueError if True. 264 | 265 | Args: 266 | header (pysam.AlignmentFile.header): the header from which to extract reference sequence lengths 267 | xx (float): the XX of NXX. we assume it is N50 so the default is 50 268 | 269 | Uses: 270 | self.mapping_dict (dict(int-->dict(int-->dict(int-->int)))): Nested dict with min_size, mapq, and edist keys 271 | and read pair counts as the inner values. 272 | 273 | Sets: 274 | self.refs dict(int-->str): ref_id --> ref_name mappings for the assembly 275 | self.contig_len (int): the NXX (probably N50) of the assembly based on the header 276 | self.total (int): the total length of the assembly 277 | self.contigs_greater_10k (set(str)): The set of names of contigs with length > 10Kbp 278 | self.contigs_greater_5k (set(str)): The set of names of contigs with length > 5Kbp 279 | self.contigs_greater (dict(int-->set(str))): Dictionary with minimum lengths as keys and sets of contigs as values 280 | self.command_line(str): Full command-line argument used for alignment 281 | self.bwa_command(str): Subset of self.command_line containing only the BWA options used 282 | self.samblaster(str): Command used by samblaster 283 | 284 | Raises: 285 | ValueError if header labels bamfile as coordinate sorted 286 | ''' 287 | 288 | if 'HD' in header and 'SO' in header['HD'] and header['HD']['SO'].lower().strip() == 'coordinate': 289 | raise ValueError('Error: hic_qc.py requires read name sorted input, but bamfile {} is coordinate sorted'.format(self.paths['bamfile'])) 290 | 291 | self.refs = header.references 292 | self.stats['num_refs'] = len(self.refs) 293 | 294 | self.N50, self.total_length = calc_nxx(header) 295 | self.contigs_greater_10k = set([contig['SN'] for contig in header['SQ'] if contig['LN'] > 10000]) 296 | self.contigs_greater_5k = set([contig['SN'] for contig in header['SQ'] if contig['LN'] > 5000]) 297 | 298 | self.contigs_greater = {} 299 | 300 | if self.mapping_dict is not None: 301 | for min_size in self.mapping_dict.keys(): 302 | self.contigs_greater[min_size] = set([contig['SN'] for contig in header['SQ'] if contig['LN'] > min_size]) 303 | 304 | # TODO: add more robust logic to different BAM headers, and/or comment the assumptions made in this code 305 | if 'PG' in header and 'bwa' in header['PG'][0]['CL']: 306 | self.bwa_command_line = header['PG'][0]['CL'] 307 | if 'bwa-mem2' in self.bwa_command_line: 308 | self.bwa_command = re.search(r'(bwa-mem2 )[^//]*', self.bwa_command_line).group() 309 | else: 310 | self.bwa_command = re.search(r'(bwa )[^//]*', self.bwa_command_line).group() 311 | bwa_command_elements = self.bwa_command_line.split() 312 | full_fwd_reads = None 313 | full_rev_reads = None 314 | for token in bwa_command_elements: 315 | token_proc = token.strip().lower() 316 | if token_proc.endswith('.fasta') or token_proc.endswith('.fa') or token_proc.endswith('.fna') \ 317 | or token_proc.endswith('.fasta.gz') or token_proc.endswith('.fa.gz') or token_proc.endswith('fna.gz'): 318 | self.ref_assembly = os.path.basename(token) 319 | elif token_proc.endswith('_r1.fastq') or token_proc.endswith('_r1.fq') \ 320 | or token_proc.endswith('_r1.fastq.gz') or token_proc.endswith('_r1.fq.gz'): 321 | self.fwd_hic_reads = os.path.basename(token) 322 | full_fwd_reads = token.strip() 323 | elif token_proc.endswith('_r2.fastq') or token_proc.endswith('_r2.fq') \ 324 | or token_proc.endswith('_r2.fastq.gz') or token_proc.endswith('_r2.fq.gz'): 325 | self.rev_hic_reads = os.path.basename(token) 326 | full_rev_reads = token.strip() 327 | files_matched = False 328 | if full_fwd_reads is not None and os.path.exists(full_fwd_reads) and \ 329 | full_rev_reads is not None and os.path.exists(full_rev_reads): 330 | if filecmp.cmp(full_fwd_reads, full_rev_reads, shallow=True): 331 | files_matched = True 332 | if os.path.exists(self.fwd_hic_reads) and os.path.exists(self.rev_hic_reads): 333 | #do a shallow check first - if the file stats don't match, the files don't match, so don't do a full comparison 334 | if filecmp.cmp(self.fwd_hic_reads, self.rev_hic_reads, shallow=True): 335 | files_matched = True 336 | if files_matched or (self.fwd_hic_reads is not None and self.fwd_hic_reads == self.rev_hic_reads) or (full_fwd_reads is not None and full_fwd_reads == full_rev_reads) \ 337 | or (self.fwd_hic_reads == "forward Hi-C reads not found") or (self.rev_hic_reads == "reverse Hi-C reads not found"): 338 | self.fwd_hic_reads = '{0}'.format(self.fwd_hic_reads) 339 | self.rev_hic_reads = '{0}'.format(self.rev_hic_reads) 340 | 341 | else: 342 | self.bwa_command = 'BWA command not found' 343 | 344 | if 'PG' in header and len(header['PG']) > 1 and 'samblaster ' in header['PG'][1]['CL']: 345 | self.samblaster = header['PG'][1]['CL'] 346 | else: 347 | self.samblaster = 'samblaster command not found' 348 | 349 | def process_pair(self, a, b): 350 | '''Extract stats from a pair of reads. 351 | Updates per read and per mapped pair stats separately. 352 | 353 | Args: 354 | a (pysam.AlignedSegment) One read in pair 355 | b (pysam.AlignedSegment) Other read in pair 356 | ''' 357 | 358 | self.stats['total_read_pairs'] += 1 359 | 360 | self.update_read_stats(a) 361 | self.update_read_stats(b) 362 | 363 | if self.is_noninformative_read_pair(a, b): 364 | self.stats['noninformative_read_pairs'] += 1 365 | elif self.is_informative_pair(a, b): 366 | self.stats['informative_pairs'] += 1 367 | 368 | if not a.is_unmapped and not b.is_unmapped: 369 | self.update_mapped_pair_stats(a, b) 370 | 371 | def update_read_stats(self, read): 372 | '''Update per read stats based on given read. 373 | 374 | Args: 375 | read (pysam.AlignedSegment): read to extract stats from 376 | ''' 377 | 378 | self.stats['total_reads'] += 1 379 | if read.is_unmapped: 380 | self.stats['unmapped_reads'] += 1 381 | elif read.mapping_quality == 0: 382 | self.stats['mapq0_reads'] += 1 383 | if read.has_tag('SA'): 384 | self.stats['split_reads'] += 1 385 | if read.is_duplicate: 386 | self.stats['duplicate_reads'] += 1 387 | 388 | def update_mapped_pair_stats(self, a, b): 389 | '''Update mapped pair stats given a pair of reads. 390 | 391 | Args: 392 | a (pysam.AlignedSegment): One read 393 | b (pysam.AlignedSegment): Other read 394 | ''' 395 | 396 | is_high_qual_pair = self.is_high_qual_pair(a, b) 397 | 398 | if is_high_qual_pair: 399 | self.stats['total_read_pairs_hq'] += 1 400 | 401 | if a.reference_name != b.reference_name: 402 | self.stats['intercontig_pairs'] += 1 403 | 404 | if is_high_qual_pair: 405 | self.stats['intercontig_pairs_hq'] += 1 406 | if a.reference_name in self.contigs_greater_10k and b.reference_name in self.contigs_greater_10k: 407 | self.stats['pairs_intercontig_hq_gt10kbp'] += 1 408 | 409 | refa_stub = a.reference_name.split('.')[0] 410 | refb_stub = b.reference_name.split('.')[0] 411 | 412 | if refa_stub != refb_stub: 413 | self.stats['different_ref_stub_pairs'] += 1 414 | 415 | if a.reference_name in self.contigs_greater_5k and b.reference_name in self.contigs_greater_5k: 416 | if min(a.mapping_quality, b.mapping_quality) > 0 and not any([a.is_duplicate, b.is_duplicate]): 417 | self.stats['proximo_usable_rp'] += 1 418 | if is_high_qual_pair: 419 | self.stats['proximo_usable_rp_hq'] += 1 420 | 421 | else: 422 | self.stats['total_pairs_on_same_contig'] += 1 423 | if (a.is_reverse and b.is_reverse) or (not a.is_reverse and not b.is_reverse): 424 | self.stats['pairs_on_same_strand'] += 1 425 | dist = abs(a.reference_start - b.reference_start) 426 | self.dists[dist] += 1 427 | 428 | if is_high_qual_pair: 429 | self.stats['pairs_intracontig_hq'] += 1 430 | if dist > 10000: 431 | self.stats['pairs_intracontig_hq_gt10kbp'] += 1 432 | if (a.is_reverse and b.is_reverse) or (not a.is_reverse and not b.is_reverse): 433 | self.stats['pairs_on_same_strand_hq'] += 1 434 | 435 | if dist > 10000: 436 | self.stats['pairs_greater_10k'] += 1 437 | if dist == 0: 438 | self.stats['zero_dist_pairs'] += 1 439 | 440 | ## Additional stats for dynamo table. 441 | if dist < 0: 442 | raise ValueError('Error: Distance between reads is less than zero.') 443 | elif dist < 1e3: 444 | self.stats['reads_spanning_up_to_1k'] += 1 445 | elif dist < 1e4: 446 | self.stats['reads_spanning_1k_to_10k'] += 1 447 | elif dist < 1e5: 448 | self.stats['reads_spanning_10k_to_100k'] += 1 449 | elif dist < 1e6: 450 | self.stats['reads_spanning_100k_to_1000k'] += 1 451 | else: 452 | self.stats['reads_spanning_greater_than_1000k'] += 1 453 | 454 | if a.reference_name in self.contigs_greater_10k: 455 | self.stats['pairs_on_contigs_greater_10k'] += 1 456 | if is_high_qual_pair: 457 | self.stats['pairs_on_contigs_greater_10k_hq'] += 1 458 | if dist > 10000: 459 | self.stats['pairs_greater_10k_on_contigs_greater_10k_hq'] += 1 460 | if dist > 10000: 461 | self.stats['pairs_greater_10k_on_contigs_greater_10k'] += 1 462 | 463 | if self.mapping_dict is not None and \ 464 | not (a.is_duplicate or b.is_duplicate): 465 | self.update_rp_array(a, b) 466 | 467 | def update_rp_array(self, a, b): 468 | '''Update nested dict of mapping stats based on current read pair a, b. 469 | 470 | Uses: 471 | self.rp_stats (list(int)): List of minimum insert sizes sorted from low to high 472 | self.mq_stats (list(int)): List of minimum mapq values sorted from low to high 473 | self.edist_stats (list(int)): List of maximum edit distances sorted from high to low 474 | 475 | Modifies: 476 | self.mapping_dict (dict(int-->dict(int-->dict(int-->int)))): Nested dict with min_size, mapq, and edist keys 477 | and read pair counts as the inner values. 478 | ''' 479 | mq = min(a.mapping_quality, b.mapping_quality) 480 | isize = abs(a.reference_start - b.reference_start) 481 | edist = max(a.get_tag('NM'), b.get_tag('NM')) 482 | 483 | for min_size in self.rp_stats: 484 | if isize >= min_size: 485 | for mapq in self.mq_stats: 486 | if mq >= mapq: 487 | for ed in self.edist_stats: 488 | if edist <= ed: 489 | self.mapping_dict[min_size][mapq][ed] += 1 490 | 491 | def is_noninformative_read_pair(self, a, b): 492 | is_noninformative = False 493 | if a.is_unmapped or b.is_unmapped: 494 | is_noninformative = True 495 | elif a.is_duplicate or b.is_duplicate: 496 | is_noninformative = True 497 | elif a.mapping_quality == 0 or b.mapping_quality == 0: 498 | is_noninformative = True 499 | elif a.reference_name == b.reference_name: 500 | if abs(a.reference_start - b.reference_start) == 0: 501 | is_noninformative = True 502 | return is_noninformative 503 | 504 | def is_informative_pair(self, a, b): 505 | is_informative = True 506 | if a.is_unmapped or b.is_unmapped: 507 | is_informative = False 508 | elif a.is_duplicate or b.is_duplicate: 509 | is_informative = False 510 | elif a.mapping_quality == 0 or b.mapping_quality == 0: 511 | is_informative = False 512 | elif a.reference_name == b.reference_name and \ 513 | abs(a.reference_start - b.reference_start) < 10000: 514 | is_informative = False 515 | return is_informative 516 | 517 | def is_high_qual_pair(self, a, b): 518 | return min(a.mapping_quality, b.mapping_quality) >= 20 and \ 519 | max(a.get_tag('NM'), b.get_tag('NM')) <= 5 and \ 520 | not a.is_duplicate and not b.is_duplicate 521 | 522 | def update_dup_stats(self): 523 | '''Update lists of duplication statistics. 524 | ''' 525 | 526 | self.total_array.append(self.stats['total_reads']) 527 | self.non_dup_array.append(self.stats['total_reads'] - self.stats['duplicate_reads']) 528 | 529 | def finalize_stats(self): 530 | '''Finalize stats from a bam file after reads are processed. 531 | ''' 532 | self.total_array = np.array(self.total_array) 533 | self.non_dup_array = np.array(self.non_dup_array) 534 | if self.stats['pairs_on_contigs_greater_10k'] > 0: 535 | self.stats['proportion_pairs_greater_10k_on_contigs_greater_10k'] = self.stats['pairs_greater_10k_on_contigs_greater_10k'] / \ 536 | self.stats['pairs_on_contigs_greater_10k'] 537 | else: 538 | self.stats['proportion_pairs_greater_10k_on_contigs_greater_10k'] = 0 539 | 540 | if len(self.contigs_greater_5k) > 0: 541 | self.stats['proximo_usable_rp_per_ctg_gt_5k'] = self.stats['proximo_usable_rp'] / len(self.contigs_greater_5k) 542 | self.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = self.stats['proximo_usable_rp_hq'] / len(self.contigs_greater_5k) 543 | self.stats['proximo_usable_rp_hq_per_ctg_gt_5k_per_million'] = self.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] / (self.stats['total_read_pairs'] / 1e6) 544 | else: 545 | self.stats['proximo_usable_rp_per_ctg_gt_5k'] = 0 546 | self.stats['proximo_usable_rp_hq_per_ctg_gt_5k'] = 0 547 | self.stats['proximo_usable_rp_hq_per_ctg_gt_5k_per_million'] = 0 548 | 549 | if self.mapping_dict is not None: 550 | self.write_mapping_stats() 551 | 552 | # We are stricter on wanting a low number of dupes when it looks like we are only looking at a QC amount of sequencing (<10M read pairs) 553 | self.allowed_dupe_percentage = 1.0 if self.stats['total_read_pairs'] > 1e7 else 0.5 554 | 555 | def write_mapping_stats(self): 556 | with open('{}.mapping_stats.tsv'.format(self.paths['outfile_prefix']), 'w') as outfile: 557 | print('edist', 'mapq', 'min_size', 'count', sep='\t', file=outfile) 558 | for min_size in self.rp_stats: 559 | for mapq in self.mq_stats: 560 | for ed in self.edist_stats: 561 | count = self.mapping_dict[min_size][mapq][ed] 562 | print(ed, mapq, min_size, count, sep='\t', file=outfile) 563 | 564 | if self.mapping_dict is not None: 565 | self.write_mapping_stats() 566 | 567 | def write_mapping_stats(self): 568 | with open('{}.mapping_stats.tsv'.format(self.paths['outfile_prefix']), 'w') as outfile: 569 | print('edist', 'mapq', 'min_size', 'count', sep='\t', file=outfile) 570 | for min_size in self.rp_stats: 571 | for mapq in self.mq_stats: 572 | for ed in self.edist_stats: 573 | count = self.mapping_dict[min_size][mapq][ed] 574 | print(ed, mapq, min_size, count, sep='\t', file=outfile) 575 | 576 | def plot_histograms(self): 577 | '''Make the read distance long, short, and log_log histograms using matplotlib and write them to disk. 578 | 579 | Args: 580 | self.dists (dict(int, int) of mate distances and counts): Distances to plot in histogram. 581 | self.num_pairs (int): number of read pairs analyzed 582 | 583 | Uses: 584 | self.paths['outfile_prefix'] (str): Path prefix for output files. 585 | ''' 586 | 587 | num_dists = sum(self.dists.values()) 588 | num_pairs = self.stats['total_read_pairs'] 589 | title_string = '\nMate distance distribution for first {} read pairs for sample\n{}'.format(num_pairs, 590 | self.paths['bamname']) 591 | key_len = len(self.dists) 592 | 593 | long_hist_path = self.paths['outfile_prefix'] + '_long.png' 594 | fig1, ax = plt.subplots(1) 595 | if key_len > 0: 596 | plt.hist(list(self.dists.keys()), weights=list(self.dists.values()), bins=50, edgecolor='black', color='red') 597 | 598 | ax.set_ylim(0.5, max(num_dists * 2, 1)) 599 | plt.yscale('log', nonpositive='clip') 600 | plt.title(title_string) 601 | plt.xlabel('Distance between read pair mates in Hi-C mapping (same contig)') 602 | plt.ylabel('Number of reads') 603 | else: 604 | plt.title('Warning: No read pair distribution to plot') 605 | fig1.savefig(long_hist_path) 606 | plt.close(fig1) 607 | self.paths['long_hist'] = long_hist_path 608 | 609 | fig2, ax = plt.subplots(1) 610 | short_hist_path = self.paths['outfile_prefix'] + '_short.png' 611 | 612 | if key_len > 0: 613 | plt.hist(list(self.dists.keys()), weights=list(self.dists.values()), bins=range(0, 20000, 500), edgecolor='black', color='red') 614 | ax.set_xlim(0, 20000) 615 | ax.set_ylim(0.5, num_pairs * 2) 616 | plt.yscale('log', nonpositive='clip') 617 | plt.title(title_string) 618 | plt.xlabel('Distance between read pair mates in Hi-C mapping (same contig)') 619 | plt.ylabel('Number of reads') 620 | else: 621 | plt.title('Warning: No read pair distribution to plot') 622 | fig2.savefig(short_hist_path) 623 | plt.close(fig2) 624 | self.paths['short_hist'] = short_hist_path 625 | 626 | fig3, ax = plt.subplots(1) 627 | log_log_hist_path = self.paths['outfile_prefix'] + '_log_log.png' 628 | 629 | offset_dists = {} 630 | for key, value in self.dists.items(): 631 | offset_dists[key+1] = value 632 | 633 | if key_len > 0: 634 | min_dist = min(self.dists.keys()) 635 | max_dist = max(self.dists.keys()) 636 | 637 | plt.hist(list(offset_dists.keys()), 638 | weights=list(offset_dists.values()), 639 | bins=np.logspace(np.log10(min_dist+1), 640 | np.log10(max_dist), 641 | 50), 642 | log=True, edgecolor='black', color='red') 643 | ax.set_ylim(0.5, max(num_pairs * 2, 1)) 644 | plt.yscale('log', nonpositive='clip') 645 | plt.xscale('log') 646 | plt.xlim(left=1) 647 | plt.title(title_string) 648 | plt.xlabel('Distance between read pair mates in Hi-C mapping (same contig, log scale)') 649 | plt.ylabel('Number of reads (log scale)') 650 | plt.tight_layout() 651 | else: 652 | plt.title('Warning: No read pair distribution to plot') 653 | 654 | fig3.savefig(log_log_hist_path) 655 | plt.close(fig3) 656 | 657 | self.paths['log_log_hist'] = log_log_hist_path 658 | 659 | fig4, ax = plt.subplots(1) 660 | log_log_norm_hist_path = self.paths['outfile_prefix'] + '_log_log_norm.png' 661 | 662 | offset_dists = {} 663 | for key, value in self.dists.items(): 664 | offset_dists[key+1] = value 665 | 666 | if key_len > 0: 667 | min_dist = min(self.dists.keys()) 668 | max_dist = max(self.dists.keys()) 669 | 670 | plt.hist(list(offset_dists.keys()), 671 | weights=list(offset_dists.values()), 672 | bins=np.logspace(np.log10(min_dist+1), 673 | np.log10(max_dist), 674 | 50), 675 | log=True, edgecolor='black', color='red', density=True) 676 | ax.set_ylim(0.0001, 1.0) 677 | plt.yscale('log', nonpositive='clip') 678 | plt.xscale('log') 679 | plt.xlim(left=1) 680 | plt.title(title_string) 681 | plt.xlabel('Distance between read pair mates in Hi-C mapping (same contig, log scale)') 682 | plt.ylabel('Density of reads (density, log scale)') 683 | plt.tight_layout() 684 | else: 685 | plt.title('Warning: No read pair distribution to plot') 686 | 687 | fig4.savefig(log_log_norm_hist_path) 688 | plt.close(fig4) 689 | 690 | self.paths['log_log_norm_hist'] = log_log_norm_hist_path 691 | 692 | def html_from_judgement(self): 693 | '''Set a formatted HTML string based on two judgment bool values 694 | Uses: 695 | self.judge_good (bool): does the hi-c library show characteristics of 'goodness', e.g. many long-distance contacts etc. 696 | self.judge_bad (bool): does the hi-c library show 'bad' characteristics, e.g. zero-distance reads or too many duplicates. 697 | Sets: 698 | self.judge_html (str): an HTML string to be substituted into the report to subjectively grade the assembly. 4 possibilities. 699 | Raises: 700 | ValueError: if impossible logical situations occur given two bools. 701 | 702 | ''' 703 | if self.judge_good and not self.judge_bad: 704 | self.judge_html = 'SUFFICIENT' 705 | elif not self.judge_good and self.judge_bad: 706 | self.judge_html = 'INSUFFICIENT' 707 | elif self.judge_good and self.judge_bad: 708 | self.judge_html = 'MIXED RESULTS' 709 | elif not self.judge_good and not self.judge_bad: 710 | self.judge_html = 'LOW SIGNAL' 711 | else: 712 | raise ValueError('logical impossibility!') 713 | 714 | # driving metrics 715 | if self.good_same_strand: 716 | if float(self.stats['pairs_on_same_strand_hq']) / max(self.stats['pairs_intracontig_hq'], 1) > 0.999: 717 | self.same_strand_hq_html = '{0}' 718 | else: 719 | self.same_strand_hq_html = '{0}' 720 | else: 721 | self.same_strand_hq_html = '{0}' 722 | 723 | if self.good_informative_read_pairs: 724 | self.informative_read_pairs_html = '{0}' 725 | else: 726 | self.informative_read_pairs_html = '{0}' 727 | 728 | # other good metrics 729 | if self.good_long_contacts: 730 | self.long_contacts_html = '{0}' 731 | else: 732 | self.long_contacts_html = '{0}' 733 | 734 | if self.good_intercontig_contacts: 735 | self.intercontig_hq_contacts_html = '{0}' 736 | else: 737 | self.intercontig_hq_contacts_html = '{0}' 738 | 739 | if self.good_usable_reads: 740 | self.usable_hq_gt_5k_html = '{0}' 741 | else: 742 | self.usable_hq_gt_5k_html = '{0}' 743 | 744 | if self.good_usable_reads_per_million: 745 | self.usable_hq_gt_5k__per_million_html = '{0}' 746 | else: 747 | self.usable_hq_gt_5k__per_million_html = '{0}' 748 | 749 | # noninformative reads breakdown 750 | if not self.bad_noninformative_read_pairs: 751 | self.noninformative_read_pairs_html = '{0}' 752 | else: 753 | self.noninformative_read_pairs_html = '{0}' 754 | 755 | if not self.high_dupe: 756 | self.high_dupe_html = '{0}' 757 | else: 758 | self.high_dupe_html = '{0}' 759 | 760 | if not self.many_zero_dist_pairs: 761 | self.many_zero_dist_pairs_html = '{0}' 762 | else: 763 | self.many_zero_dist_pairs_html = '{0}' 764 | 765 | if not self.many_unmapped_reads: 766 | self.many_unmapped_reads_html = '{0}' 767 | else: 768 | self.many_unmapped_reads_html = '{0}' 769 | 770 | if not self.many_mapq_zero_reads: 771 | self.many_zero_mapq_reads_html = '{0}' 772 | else: 773 | self.many_zero_mapq_reads_html = '{0}' 774 | 775 | def pass_judgement(self): 776 | '''Pass judgement on the library according to certain mostly subjective ideas about what is good 777 | 778 | Uses: 779 | self.stats ({str: float/str}): mapping of lib characteristics to their values 780 | 781 | Sets: 782 | self.judge_good (bool): does the hi-c library show characteristics of 'goodness', e.g. many same strand contacts. 783 | self.judge_bad (bool): does the hi-c library show 'bad' characteristics, e.g. zero-mapq reads or too many duplicates. 784 | self.judge_html (str): an HTML string to put into pass/fail box 785 | ''' 786 | # these metrics drive the subjective quality judgement 787 | self.good_same_strand = float(self.stats['pairs_on_same_strand_hq']) / \ 788 | max(self.stats['pairs_intracontig_hq'], 1) > \ 789 | self.min_same_strand_hq_percentage 790 | self.good_informative_read_pairs = float(self.stats['informative_pairs']) / \ 791 | max(self.stats['total_read_pairs'], 1) > \ 792 | self.min_informative_read_pairs_percentage 793 | 794 | # other good metrics 795 | self.good_long_contacts = float(self.stats['pairs_greater_10k_on_contigs_greater_10k_hq']) / \ 796 | max(self.stats['pairs_on_contigs_greater_10k_hq'], 1) > \ 797 | self.min_long_contact_percentage 798 | self.good_intercontig_contacts = float(self.stats['pairs_intercontig_hq_gt10kbp']) / \ 799 | max(self.stats['total_read_pairs_hq'], 1) > \ 800 | self.min_intercontig_contact_percentage 801 | self.good_usable_reads = float(self.stats['proximo_usable_rp_hq_per_ctg_gt_5k']) > \ 802 | self.min_usable_reads_per_contig 803 | self.good_usable_reads_per_million = float(self.stats['proximo_usable_rp_hq_per_ctg_gt_5k_per_million']) > \ 804 | self.min_usable_reads_per_contig_per_million 805 | 806 | # noninformative read breakdown 807 | # We are stricter on wanting a low number of dupes when it looks like we are only looking at a QC amount of sequencing (<10M read pairs) 808 | self.bad_noninformative_read_pairs = float(self.stats['noninformative_read_pairs']) / \ 809 | max(self.stats['total_read_pairs'], 1) > \ 810 | self.max_noninformative_read_pair_percentage 811 | self.high_dupe = float(self.stats['duplicate_reads']) / \ 812 | max(self.stats['total_reads'], 1) > \ 813 | self.max_dupe_percentage * \ 814 | self.allowed_dupe_percentage 815 | self.many_zero_dist_pairs = float(self.stats['zero_dist_pairs']) / \ 816 | max(self.stats['total_read_pairs'], 1) > \ 817 | self.max_zero_dist_percentage 818 | self.many_unmapped_reads = float(self.stats['unmapped_reads']) / \ 819 | max(self.stats['total_reads'], 1) > \ 820 | self.max_unmapped_percentage 821 | self.many_mapq_zero_reads = float(self.stats['mapq0_reads']) / \ 822 | max(self.stats['total_reads'], 1) > \ 823 | self.max_zero_mapq0_percentage 824 | 825 | self.judge_good = self.good_same_strand 826 | self.judge_bad = not self.good_informative_read_pairs 827 | 828 | self.html_from_judgement() 829 | 830 | def stringify_stats(self): 831 | '''Convert stats to output dictionary with pretty strings and percents. 832 | 833 | Uses: 834 | self.to_percents ({str: (int, int)}): Mapping of keys to numerator, denominator pair for conversion to percents. 835 | self.to_round (set(str)): Set of keys from stats dict to round. 836 | self.convert_to_pairs (set(str)): Set of keys from stats dict that represent per read statistics. 837 | self.per_pair_metrics (set(str)): Set of keys from stats dict that represent per read pair statistics. 838 | self.paths ({str: str}): Mapping of names to paths. 839 | 840 | Sets: 841 | self.other_stats ({str: (float, str)}): Mapping of keys to value, format pair. 842 | self.out_stats ({str: str}): Mapping of stat keys to formatted strings. 843 | ''' 844 | 845 | # Dict of key --> (value, fmt) pairs for items that aren't counts 846 | self.other_stats = { 847 | 'N50': (self.N50, '{:,}'), 848 | 'contigs': (len(self.refs), '{:,}'), 849 | 'contigs_greater_10k': (len(self.contigs_greater_10k), '{:,}'), 850 | 'contigs_greater_5k': (len(self.contigs_greater_5k), '{:,}'), 851 | 'total_length': (self.total_length, '{:,}'), 852 | 'total_reads': (self.stats['total_reads'], '{:,}'), 853 | 'judgment': (self.judge_html, '{}'), 854 | 'qc_purpose': (self.qc_purpose, '{}'), 855 | 'same_strand_threshold': (100.0 * self.min_same_strand_hq_percentage, '{}'), 856 | 'informative_read_pairs_threshold': (100.0 * self.min_informative_read_pairs_percentage, '{}'), 857 | 'noninformative_read_pairs_threshold': (100.0 * self.max_noninformative_read_pair_percentage, '{}'), 858 | 'long_contacts_threshold': (100.0 * self.min_long_contact_percentage, '{}'), 859 | 'intercontig_hq_contacts_threshold': (100.0 * self.min_intercontig_contact_percentage, '{}'), 860 | 'usable_hq_gt_5k_threshold': (self.min_usable_reads_per_contig, '{}'), 861 | 'min_usable_reads_per_contig_per_million_threshold': (self.min_usable_reads_per_contig_per_million, '{}'), 862 | 'high_dupe_threshold': (100.0 * self.max_dupe_percentage * self.allowed_dupe_percentage, '{}'), 863 | 'many_zero_dist_threshold': (100.0 * self.max_zero_dist_percentage, '{}'), 864 | 'many_zero_mapq_threshold': (100.0 * self.max_zero_mapq0_percentage, '{}'), 865 | 'many_unmapped_threshold': (100.0 * self.max_unmapped_percentage, '{}'), 866 | 'alignment_command_line': (self.bwa_command, '{}'), 867 | 'samblaster': (self.samblaster, '{}'), 868 | 'lib_enzyme': (', '.join(self.lib_enzyme), '{}'), 869 | 'ref_assembly': (self.ref_assembly, '{}'), 870 | 'fwd_hic_reads': (self.fwd_hic_reads, '{}'), 871 | 'rev_hic_reads': (self.rev_hic_reads, '{}'), 872 | } 873 | self.out_stats = {} 874 | for key, (num, denom) in self.to_percents.items(): 875 | try: 876 | self.out_stats[key] = '{:.2f}%'.format((self.stats[num] / self.stats[denom]) * 100) 877 | except ZeroDivisionError as e: 878 | self.out_stats[key] = 'NaN' 879 | 880 | for key in self.to_round: 881 | self.out_stats[key] = '{:.2f}'.format(self.stats[key]) 882 | 883 | for item in self.convert_to_pairs: 884 | self.out_stats[item] = '{:,}'.format(self.stats[item] // 2) 885 | 886 | for item in self.per_pair_metrics: 887 | self.out_stats[item] = '{:,}'.format(self.stats[item]) 888 | 889 | for item in self.paths: 890 | if item == "bamname": 891 | self.out_stats[item] = self.paths[item] 892 | else: 893 | self.out_stats[item] = os.path.abspath(self.paths[item]) 894 | 895 | for key, value in self.contigs_greater.items(): 896 | key_str = 'contigs_greater_{:.0f}k'.format(key / 1000) 897 | self.out_stats[key_str] = '{:,}'.format(len(value)) 898 | 899 | for key, (value, fmt) in self.other_stats.items(): 900 | self.out_stats[key] = fmt.format(value) 901 | 902 | # driving stats 903 | self.out_stats['same_strand_hq_html'] = self.same_strand_hq_html.format(self.out_stats['perc_pairs_on_same_strand_hq']) 904 | self.out_stats['informative_read_pairs_html'] = self.informative_read_pairs_html.format(self.out_stats['perc_informative_read_pairs']) 905 | self.out_stats['noninformative_read_pairs_html'] = self.noninformative_read_pairs_html.format(self.out_stats['perc_noninformative_read_pairs']) 906 | # other good metrics 907 | self.out_stats['long_contacts_html'] = self.long_contacts_html.format(self.out_stats['perc_pairs_intra_hq_gt10kbp']) 908 | self.out_stats['intercontig_hq_contacts_html'] = self.intercontig_hq_contacts_html.format(self.out_stats['perc_intercontig_pairs_hq_gt10kbp']) 909 | self.out_stats['usable_hq_gt_5k_html'] = self.usable_hq_gt_5k_html.format(self.out_stats['proximo_usable_rp_hq_per_ctg_gt_5k']) 910 | self.out_stats['usable_hq_gt_5k_per_million_html'] = self.usable_hq_gt_5k__per_million_html.format(self.out_stats['proximo_usable_rp_hq_per_ctg_gt_5k_per_million']) 911 | # noninformative breakdown 912 | self.out_stats['high_dupe_html'] = self.high_dupe_html.format(self.out_stats['perc_duplicate_reads']) 913 | self.out_stats['many_zero_dist_pairs_html'] = self.many_zero_dist_pairs_html.format(self.out_stats['perc_zero_dist_pairs']) 914 | self.out_stats['many_unmapped_reads_html'] = self.many_unmapped_reads_html.format(self.out_stats['perc_unmapped_reads']) 915 | self.out_stats['many_zero_mapq_reads_html'] = self.many_zero_mapq_reads_html.format(self.out_stats['perc_mapq0_reads']) 916 | 917 | self.out_stats['version'] = HICQC_VERSION 918 | 919 | def log_stats(self, count_diff_refname_stub=False): 920 | '''Log statistical summary. 921 | 922 | Uses: 923 | self.paths ({str: str}): Mapping of names to paths. 924 | self.out_stats ({str: str}): Mapping of stat keys to formatted strings. 925 | count_diff_refname_stub (bool): Whether we are counting the contig name stub differences. 926 | ''' 927 | 928 | ('Histograms written to:', self.paths['long_hist'], self.paths['short_hist'], self.paths['log_log_hist']) 929 | 930 | self.logger.info('Number of contigs (more is harder):') 931 | self.logger.info(self.out_stats['contigs']) 932 | 933 | self.logger.info('Number of contigs greater than 10KB (longer contigs are better):') 934 | self.logger.info(self.out_stats['contigs_greater_10k']) 935 | 936 | self.logger.info('N50 of input assembly (longer contigs are better):') 937 | self.logger.info(self.out_stats['N50']) 938 | 939 | self.logger.info('Length of input assembly (bigger is harder):') 940 | self.logger.info(self.out_stats['total_length']) 941 | 942 | self.logger.info('Counts of zero distances (many is a sign of bad prep):') 943 | self.logger.info('{} of total {} {}'.format( 944 | self.out_stats['zero_dist_pairs'], 945 | self.out_stats['total_read_pairs'], 946 | self.out_stats['perc_zero_dist_pairs']) 947 | ) 948 | 949 | self.logger.info('Count of same-contig read pairs with distance > 10KB (many is a sign of good prep):') 950 | self.logger.info('{} of total {} {}'.format( 951 | self.out_stats['pairs_greater_10k'], 952 | self.out_stats['total_read_pairs'], 953 | self.out_stats['perc_pairs_greater_10k']) 954 | ) 955 | 956 | self.logger.info('Proportion of reads mapping to contigs > 10 Kbp with inserts > 10 Kbp:') 957 | self.logger.info('{} of total {} {}'.format( 958 | self.out_stats['pairs_greater_10k_on_contigs_greater_10k'], 959 | self.out_stats['pairs_on_contigs_greater_10k'], 960 | self.out_stats['perc_pairs_greater_10k_on_contigs_greater_10k']) 961 | ) 962 | 963 | self.logger.info('Count of read pairs with mates mapping to different chromosomes/contigs ' \ 964 | '(sign of good prep IF same genome):') 965 | self.logger.info('{} of total {} {}'.format( 966 | self.out_stats['intercontig_pairs'], 967 | self.out_stats['total_read_pairs'], 968 | self.out_stats['perc_intercontig_pairs']) 969 | ) 970 | 971 | self.logger.info('Count of split reads (more is usually good, as indicates presence of Hi-C junction in read):') 972 | self.logger.info('{} of total {} {}'.format( 973 | self.out_stats['split_reads'], 974 | self.stats['total_reads'], 975 | self.out_stats['perc_split_reads']) 976 | ) 977 | 978 | self.logger.info('Count of MAPQ zero reads (bad, ambiguously mapped):') 979 | self.logger.info('{} of total {} {}'.format( 980 | self.out_stats['mapq0_reads'], 981 | self.out_stats['total_reads'], 982 | self.out_stats['perc_mapq0_reads']) 983 | ) 984 | 985 | self.logger.info('Count of duplicate reads (-1 if insufficient to estimate; duplicates are bad; ' \ 986 | 'WILL ALWAYS BE ZERO UNLESS BAM FILE IS PREPROCESSED TO SET THE DUPLICATES FLAG):') 987 | self.logger.info('{} of total {} {}'.format( 988 | self.out_stats['duplicate_reads'], 989 | self.out_stats['total_reads'], 990 | self.out_stats['perc_duplicate_reads']) 991 | ) 992 | 993 | if count_diff_refname_stub: 994 | self.logger.info('Count of read pairs with mates mapping to different reference groupings, ' \ 995 | 'e.g. genomes (sign of bad prep potentially):') 996 | self.logger.info('{} of total {} {}'.format( 997 | self.out_stats['different_ref_stub_pairs'], 998 | self.out_stats['total_read_pairs'], 999 | self.out_stats['perc_different_ref_stub_pairs']) 1000 | ) 1001 | 1002 | def write_stat_table(self): 1003 | '''Writes the stats as a plain text file. 1004 | 1005 | Uses: 1006 | self.out_stats ({str: str}): Mapping of stat keys to formatted strings. 1007 | self.paths['outfile_prefix'] (str): Path prefix for output files. 1008 | ''' 1009 | 1010 | tsv = self.paths['outfile_prefix'] + '.tsv' 1011 | 1012 | with open(tsv, "w") as outfile: 1013 | for k, v in self.out_stats.items(): 1014 | if k == "refs" or k == "dists": 1015 | #skip long metadata fields we don't really need 1016 | continue 1017 | print(k, v, sep="\t", file=outfile) 1018 | 1019 | def write_dists_file(self): 1020 | '''Writes the dists as a plain text file. 1021 | 1022 | Uses: 1023 | self.out_stats ({str: str}): Mapping of stat keys to formatted strings. 1024 | self.paths['outfile_prefix'] (str): Path prefix for output files. 1025 | 1026 | Args: 1027 | stat_dict ({str:str/float}): dict mapping stat labels to their values and other info. 1028 | ''' 1029 | if not self.paths['outfile_prefix'].endswith(".dists"): 1030 | outfile_name = self.paths['outfile_prefix'] + ".dists" 1031 | else: 1032 | outfile_name = self.paths['outfile_prefix'] 1033 | 1034 | with open(outfile_name, "w") as outfile: 1035 | for k, v in self.dists.items(): 1036 | print(k, v, sep="\t", file=outfile) 1037 | 1038 | def write_pdf_report(self, quiet=False): 1039 | '''Make the pdf report using the template. 1040 | Requires markdown template in the collateral directory of hic_qc. 1041 | 1042 | Uses: 1043 | self.paths['script_dir']: Path to hic_qc directory. 1044 | self.out_stats ({str: str}): Mapping of stat keys to formatted strings. 1045 | self.paths['outfile_prefix'] (str): Path prefix for output files. 1046 | ''' 1047 | options = { 1048 | 'page-size': 'A4', 1049 | 'dpi': 350, 1050 | 'margin-top': '0.75in', 1051 | 'margin-right': '0.75in', 1052 | 'margin-bottom': '0.75in', 1053 | 'margin-left': '0.75in', 1054 | 'encoding': "UTF-8", 1055 | 'custom-header': [ 1056 | ('Accept-Encoding', 'gzip') 1057 | ], 1058 | 'no-outline': None, 1059 | 'enable-local-file-access': '' 1060 | } 1061 | 1062 | if quiet: 1063 | options["quiet"] = "" 1064 | 1065 | template_path = os.path.join(self.paths['script_dir'], "collateral", "HiC_QC_report_template.md") 1066 | style_path = os.path.join(self.paths['script_dir'], "collateral", "style.css") 1067 | 1068 | if not os.path.exists(template_path): 1069 | raise FileNotFoundError("Can't find markdown template at {}! Exitting...".format( 1070 | template_path) 1071 | ) 1072 | 1073 | with open(template_path) as template_fh: 1074 | template_string = template_fh.read() 1075 | sub_str = template_string.format(**self.out_stats) # splat the statistics and path into the markdown, render as html 1076 | html = md.markdown(sub_str, extensions=['markdown.extensions.tables', 'markdown.extensions.nl2br']) 1077 | 1078 | # write out just html 1079 | with open(self.paths['outfile_prefix'] + "_qc_report.html", 'w') as html_out: 1080 | html_out.write(html) 1081 | 1082 | # print html 1083 | pdfkit.from_string(html, self.paths['outfile_prefix'] + "_qc_report.pdf", options=options, css=style_path) 1084 | 1085 | def parse_args(): 1086 | '''parse command-line args 1087 | 1088 | Args: 1089 | desc(str): program description, e.g. __file__ 1090 | 1091 | Returns: 1092 | args (dict): dict of the form {arg_name: arg_value} 1093 | ''' 1094 | parser = argparse.ArgumentParser(description=__file__) 1095 | parser.add_argument('-n', '--num_reads', default=1000000, type=int, 1096 | help='Number of reads from bam file to use. Use -1 to use all reads. Default: %(default)s') 1097 | parser.add_argument('-b', '--bam_file', required=True, type=str, 1098 | help='BAM file to evaluate for QC') 1099 | parser.add_argument('--count_diff_refname_stub', action='store_true', 1100 | help='Can be used to QC differently given reference name formatting. For internal use.') 1101 | parser.add_argument('--outfile_prefix', '-o', default='Read_mate_dist', type=str, 1102 | help='Path to which to write plots to (PNG suffix will be attached).') 1103 | parser.add_argument('--disable_report', '-d', action='store_true', 1104 | help='Disable PDF report generation (Default: %(default)s).') 1105 | parser.add_argument('--rp_stats', nargs='+', default=[0, 1, 2, 5, 10, 20, 50], 1106 | help='List of distances in Kbp to calculate RP stats for (Default: %(default)s)') 1107 | parser.add_argument('--mq_stats', nargs='+', default=[0, 1, 10, 20, 30, 40], 1108 | help='List of min MQ scores to calculate RP stats for (Default: %(default)s)') 1109 | parser.add_argument('--edist_stats', nargs='+', default=[100, 10, 5, 3, 1, 0], 1110 | help='List of max edist scores to calculate RP stats for (Default: %(default)s)') 1111 | parser.add_argument('--version', action='version', version=HICQC_VERSION) 1112 | parser.add_argument('--thresholds', default='{0}/collateral/thresholds.json'.format(os.path.dirname(os.path.realpath(__file__))), 1113 | help='JSON file containing QC thresholds (Default: %(default)s)') 1114 | parser.add_argument('--sample_type', default='genome', choices=['genome', 'metagenome'], 1115 | help='Use QC thresholds for the specified sample type (Default: %(default)s)') 1116 | parser.add_argument('--lib_enzyme', default=['unspecified'], nargs='+', type=str, 1117 | help='Name of the enzyme(s) used for Hi-C library preparation.') 1118 | 1119 | args = parser.parse_args() 1120 | 1121 | return args 1122 | 1123 | def estimate_required_num_reads(diff_contig, refs, num_pairs, target=600.0): 1124 | '''estimate the desired number of reads total based on the observed reads''' 1125 | 1126 | target_num = len(refs) * target # desired among-contig 1127 | diff_rate = float(diff_contig) / float(num_pairs) # rate of among-contig per read pair 1128 | total_num = target_num / diff_rate 1129 | return int(total_num) 1130 | 1131 | if __name__ == "__main__": 1132 | args = parse_args() 1133 | dirname = os.path.dirname(args.outfile_prefix) 1134 | if dirname != '' and not os.path.exists(dirname): 1135 | os.makedirs(dirname) 1136 | 1137 | QC = HiCQC(outfile_prefix=args.outfile_prefix, 1138 | sample_type=args.sample_type, 1139 | thresholds_file=args.thresholds, 1140 | rp_stats=args.rp_stats, 1141 | mq_stats=args.mq_stats, 1142 | edist_stats=args.edist_stats, 1143 | lib_enzyme=args.lib_enzyme 1144 | ) 1145 | 1146 | QC.parse_bam(args.bam_file, max_read_pairs=args.num_reads) 1147 | QC.pass_judgement() 1148 | QC.html_from_judgement() 1149 | QC.plot_histograms() 1150 | QC.stringify_stats() 1151 | QC.log_stats() 1152 | QC.write_stat_table() 1153 | QC.write_dists_file() 1154 | if not args.disable_report: 1155 | QC.write_pdf_report() 1156 | --------------------------------------------------------------------------------