├── test ├── usage-example │ ├── test.vcf.gz │ └── usage-example └── Snakemake ├── rhocall ├── __main__.py ├── __init__.py ├── log.py ├── win.py ├── prints.py ├── run_tally.py ├── run_aggregate.py ├── utils.py ├── run_annotate_var.py ├── run_annotate.py ├── run_viz.py ├── run_annotate_bcfroh.py ├── run_rho.py └── cli.py ├── useful_commands ├── pyproject.toml ├── CHANGELOG.md ├── .gitignore ├── rhoviz.py ├── rhocall.py ├── README.md └── LICENSE /test/usage-example/test.vcf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dnil/rhocall/HEAD/test/usage-example/test.vcf.gz -------------------------------------------------------------------------------- /rhocall/__main__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from rhocall.cli import cli 4 | 5 | if __name__ == "__main__": 6 | # exit using whatever exit code the CLI returned 7 | sys.exit(cli()) 8 | -------------------------------------------------------------------------------- /rhocall/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | try: 3 | from importlib.metadata import version 4 | except ImportError: # Backport support for importlib metadata on Python 3.7 5 | from importlib_metadata import version 6 | 7 | __version__ = version("rhocall") 8 | -------------------------------------------------------------------------------- /useful_commands: -------------------------------------------------------------------------------- 1 | bcftools roh --AF-file anon_SweGen_161019_snp_freq_hg19.tab.gz -I 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.bcf > 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh 2 | bcftools query -f'%CHROM\t%POS\t%REF,%ALT\t%INFO/AF\n' anon-SweGen_STR_NSPHS_1000samples_snp_freq_hg19.vcf.gz | bgzip -c > anon_SweGen_161019_snp_freq_hg19.tab.gz 3 | rhocall tally 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh 4 | -------------------------------------------------------------------------------- /test/usage-example/usage-example: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Author: petr.danecek@sanger 4 | # 5 | # About: This script gives an example of using bcftools/roh 6 | # 7 | 8 | # The FORMAT/PL annotation is not present, we go with FORMAT/GT, 9 | # see the -G option. Also, the VCF does not contain allele 10 | # frequency information and there is just one sample so it 11 | # cannot be estimated on the fly. Hence we use a default value 12 | # of 0.4. 13 | 14 | bcftools roh test.vcf.gz -G30 --AF-dflt 0.4 > out.txt 15 | 16 | -------------------------------------------------------------------------------- /rhocall/log.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | 4 | LEVELS = {0: "ERROR", 1: "WARNING", 2: "INFO", 3: "DEBUG"} 5 | 6 | 7 | def configure_stream(level="WARNING"): 8 | """Configure root logger using a standard stream handler. 9 | 10 | Args: 11 | level (string, optional): lowest level to log to the console 12 | 13 | Returns: 14 | logging.RootLogger: root logger instance with attached handler 15 | """ 16 | # get the root logger 17 | root_logger = logging.getLogger() 18 | # set the logger level to the same as will be used by the handler 19 | root_logger.setLevel(level) 20 | 21 | # customize formatter, align each column 22 | template = "[%(asctime)s] %(name)-25s %(levelname)-8s %(message)s" 23 | formatter = logging.Formatter(template) 24 | 25 | # add a basic STDERR handler to the logger 26 | console = logging.StreamHandler() 27 | console.setLevel(level) 28 | console.setFormatter(formatter) 29 | 30 | root_logger.addHandler(console) 31 | return root_logger 32 | -------------------------------------------------------------------------------- /test/Snakemake: -------------------------------------------------------------------------------- 1 | rule frequency_file: 2 | input: 3 | "anon-SweGen_STR_NSPHS_1000samples_snp_freq_hg19.vcf.gz" 4 | output: 5 | "anon_SweGen_161019_snp_freq_hg19.tab.gz" 6 | shell: 7 | "bcftools query -f'%CHROM\t%POS\t%REF,%ALT\t%INFO/AF\n' {input} | bgzip -c > {output}" 8 | 9 | rule roh_file_by_bcftools: 10 | input: 11 | bcf="{sample}.bcf", 12 | freq="anon_SweGen_161019_snp_freq_hg19.tab.gz" 13 | output: 14 | "{sample}.roh" 15 | shell: 16 | "bcftools roh --AF-file {input.freq} -I {input.bcf} > {output}" 17 | 18 | # 19 | # Tally the apparently AZ and HW variants on each chromosome to detect gross AZ. 20 | # 21 | rule tally: 22 | input: 23 | "{sample}.roh" 24 | output: 25 | "{sample}.roh.tally.tsv" 26 | shell: 27 | "rhocall tally {input} -o {output}" 28 | 29 | rule aggregate: 30 | input: 31 | "{sample}.roh" 32 | output: 33 | "{sample}.roh.bed" 34 | shell: 35 | "rhocall aggregate {input} -o {output}" 36 | 37 | rule annotate: 38 | input: 39 | bed="{sample}.roh.bed", 40 | bcf="{sample}.bcf" 41 | output: 42 | "{sample}.roh.vcf" 43 | shell: 44 | "rhocall annotate -b {input.bed} -o {output} {input.bcf}" 45 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling>=1.15,<2"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "rhocall" 7 | version = "0.6" 8 | description = "Call regions of homozygosity and make tentative UPD calls" 9 | readme = "README.md" 10 | license = { text = "GPL-3.0-or-later" } 11 | authors = [ 12 | { name = "Daniel Nilsson", email = "daniel.nilsson@scilifelab.com" } 13 | ] 14 | keywords = ["VCF", "variants", "RHO", "autozygosity", "homozygosity", "UPD"] 15 | dependencies = [ 16 | "click", 17 | "cyvcf2", 18 | "numpy", 19 | "matplotlib", # for visualization 20 | ] 21 | 22 | [project.optional-dependencies] 23 | dev = [ 24 | "pytest", 25 | "flake8", 26 | "black", 27 | ] 28 | 29 | [project.scripts] 30 | rhocall = "rhocall.cli:cli" # points to click.Command object 31 | 32 | [project.urls] 33 | Repository = "https://github.com/dnil/rhocall" 34 | Changelog = "https://github.com/dnil/rhocall/blob/main/CHANGELOG.md" 35 | "Bug Tracker" = "https://github.com/dnil/rhocall/issues" 36 | Issues = "https://github.com/dnil/rhocall/issues" 37 | 38 | [tool.hatch.build.targets.sdist] 39 | include = ["rhocall", "README.md", "LICENSE", "*.md"] 40 | 41 | [tool.black] 42 | line-length = 100 43 | 44 | [tool.hatch.build.targets.wheel] 45 | -------------------------------------------------------------------------------- /rhocall/win.py: -------------------------------------------------------------------------------- 1 | class Win: 2 | """A general sequence window with one linear sum property. 3 | Outputs bed style, with a running average over the window. 4 | In this case, represents a run of autozygosity, with an average quality.""" 5 | 6 | chr = "" 7 | start = 0 8 | end = 0 9 | sum = 0 10 | count = 0 11 | print_me = False 12 | 13 | def reset(self, chr="", start=0, end=0, sum=0, count=0, print_me=False): 14 | # current window object.. 15 | self.chr = chr 16 | self.start = start 17 | self.end = end 18 | self.sum = sum 19 | self.count = count 20 | self.print_me = print_me 21 | 22 | def __init__(self, chr="", start=0, end=0, sum=0, count=0, print_me=False): 23 | self.reset(chr, start, end, sum, count, print_me) 24 | 25 | def extend(self, new_end, delta): 26 | self.end = new_end 27 | self.sum = self.sum + delta 28 | self.count = self.count + 1 29 | 30 | def dump_bed_header(self, output): 31 | output.write("#chr\tstart\tend\tAZ\tqual\n") 32 | 33 | def dump(self, output): 34 | if self.print_me: 35 | avg = float(self.sum / self.count) 36 | output.write("%s\t%d\t%d\t1\t%.2f\n" % (str(self.chr), self.start, self.end, avg)) 37 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # ChangeLog 2 | 3 | ## [0.6] 4 | ### Added 5 | - Add an option to rhocall annotate to allow selecting sample for annotation among several in ROH/VCF 6 | ### Changed 7 | - Refactor rhocall viz ratio calculation 8 | ### Fixed 9 | - Fixed rhocall viz MNV use flag 10 | 11 | ## [0.5.2] 12 | - HW and AZ are flags, set Number appropriately in VCF 13 | - Use a pyproject.toml, hatchling build 14 | 15 | ## [0.5.1] 16 | - fixed viz functionality for later versions of bcftools 17 | - viz can now produce roh bed files 18 | 19 | ## [0.5] 20 | - merged viz into the main rhocall framework 21 | - viz can now produce wig files 22 | 23 | ## [0.4] 24 | New flag --v14 to accept new bcftools roh files. 25 | 26 | ## [0.3] 27 | --version 28 | 29 | ## [0.2] 30 | 31 | Single chromosomes. Still some edge cases left for non-standard operation. 32 | Classification pending. A test set has been added, but tests not yet written. 33 | Looking at current test set performance, advise the use of bcftools v1.2 rather 34 | than v.1.3 which seems to have broken something in their ROH functionality 35 | (see bcftools #529). 36 | 37 | ## [0.1] 38 | 39 | Initial release! Passes auto-install and performs intended functions on a 40 | limited number of test samples. 41 | Many edge cases can remain. Classification of AZ variant types is only 42 | a placeholder right now. Future mode will include reading ped file, 43 | noting inheritance and sex. 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # emacs temp 92 | *~ 93 | .#* -------------------------------------------------------------------------------- /rhocall/prints.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | from rhocall import __version__ 4 | 5 | 6 | def output_bed_header(): 7 | print("#rhocall version {0}".format(__version__)) 8 | 9 | 10 | def end_block(block_chr, block_start, block_end, block_hets, block_homs): 11 | print( 12 | "{0}\t{1}\t{2}\t{3}\t{4}\t{5}".format( 13 | block_chr, block_start, block_end, block_end - block_start + 1, block_hets, block_homs 14 | ) 15 | ) 16 | 17 | 18 | def end_chr(current_chr, chr_size_spanned, chr_blocked, chr_hets, chr_homs, flag_UPD_at_fraction): 19 | flag = "Normal" 20 | 21 | if (chr_blocked / chr_size_spanned) > flag_UPD_at_fraction: 22 | if current_chr == "X" or current_chr == "chrX": 23 | flag = "HemiX" 24 | elif current_chr == "Y" or current_chr == "chrY": 25 | flag = "HemiY" 26 | elif ( 27 | current_chr == "MT" 28 | or current_chr == "chrMT" 29 | or current_chr == "M" 30 | or current_chr == "chrM" 31 | ): 32 | flag = "HemiMT" 33 | else: 34 | flag = "UPD" 35 | else: 36 | if current_chr == "X" or current_chr == "chrX": 37 | flag = "HetX" 38 | elif current_chr == "Y" or current_chr == "chrY": 39 | if chr_hets + chr_homs < 1000: 40 | flag = "NoY" 41 | 42 | flag = "HetY" 43 | elif ( 44 | current_chr == "MT" 45 | or current_chr == "chrMT" 46 | or current_chr == "M" 47 | or current_chr == "chrM" 48 | ): 49 | flag = "HetMT" 50 | 51 | print( 52 | "{0}\t1\t{1}\tCHROMOSOME_TOTAL\t{2}\t{3}\t{4}\t{5}".format( 53 | current_chr, chr_size_spanned, chr_blocked, chr_hets, chr_homs, flag 54 | ) 55 | ) 56 | -------------------------------------------------------------------------------- /rhocall/run_tally.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logger = logging.getLogger(__name__) 4 | 5 | 6 | def run_tally(roh, quality_threshold, flag_upd_at_fraction, output): 7 | """Markup VCF file using rho-calls. VCF files annotated with GENMOD style 8 | inheritance patterns are accepted.""" 9 | 10 | chrom_hw = dict() 11 | chrom_az = dict() 12 | # output chrom in order of appearance 13 | chrom_ordered_list = [] 14 | 15 | for r in roh: 16 | 17 | if r[0] == "#": 18 | continue 19 | 20 | col = r.rstrip().split("\t") 21 | chrom = str(col[0]) 22 | pos = int(col[1]) 23 | az = int(col[2]) 24 | qual = float(col[3]) 25 | 26 | if chrom not in chrom_ordered_list: 27 | chrom_ordered_list = chrom_ordered_list + [chrom] 28 | if chrom not in chrom_az: 29 | chrom_az[chrom] = 0 30 | if chrom not in chrom_hw: 31 | chrom_hw[chrom] = 0 32 | 33 | if qual >= quality_threshold: 34 | if az == 0: 35 | if chrom in chrom_hw: 36 | chrom_hw[chrom] = chrom_hw[chrom] + 1 37 | else: 38 | chrom_hw[chrom] = 1 39 | else: 40 | if chrom in chrom_az: 41 | chrom_az[chrom] = chrom_az[chrom] + 1 42 | else: 43 | chrom_az[chrom] = 1 44 | 45 | else: 46 | # ignore low quality 47 | pass 48 | 49 | output.write("chrom\thw\taz\tazf\tflag\n") 50 | for chrom in chrom_ordered_list: 51 | az_fraction = chrom_az[chrom] / (chrom_hw[chrom] + chrom_az[chrom]) 52 | flag = "" 53 | if az_fraction >= flag_upd_at_fraction: 54 | flag = "HIGH_AZ" 55 | # alert only for chromX, chromY calls? 56 | output.write( 57 | "%s\t%d\t%d\t%.2f\t%s\n" % (chrom, chrom_hw[chrom], chrom_az[chrom], az_fraction, flag) 58 | ) 59 | -------------------------------------------------------------------------------- /rhocall/run_aggregate.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logger = logging.getLogger(__name__) 4 | 5 | from .win import Win 6 | 7 | 8 | def run_aggregate(roh, quality_threshold, output): 9 | """Aggregate bcftools TSV style per variant roh calls into windowed BED file. 10 | Trust calls at or above given quality threshold.""" 11 | 12 | # current window object.. 13 | win = Win() 14 | 15 | in_win = False 16 | 17 | for r in roh: 18 | 19 | if r[0] == "#": 20 | continue 21 | 22 | col = r.rstrip().split("\t") 23 | chr = str(col[0]) 24 | pos = int(col[1]) 25 | az = int(col[2]) 26 | qual = float(col[3]) 27 | 28 | if chr != win.chr: 29 | # new chr! leave last win and dump win (if printable) 30 | # dont start new win yet - await first 1.. 31 | in_win = False 32 | win.dump(output) 33 | # clear the dumped window, setting chr to current and output false. 34 | win.reset(chr=chr, start=pos, end=pos, sum=0, count=0, print_me=False) 35 | 36 | if qual < quality_threshold: 37 | # low qual cannot start win, cannot end win - only extend 38 | if in_win and az == 1: 39 | # init new tentative window instead.. 40 | win.extend(pos, qual) 41 | continue 42 | 43 | if in_win and az == 1: 44 | # extend win 45 | win.extend(pos, qual) 46 | 47 | elif in_win and az == 0: 48 | # dump win to output, drop. 49 | win.dump(output) 50 | win.reset(chr=chr, start=pos, end=pos, sum=0, count=0, print_me=False) 51 | in_win = False 52 | 53 | elif not in_win and az == 1: 54 | in_win = True 55 | win.reset(chr=chr, start=pos, end=pos, sum=qual, count=1, print_me=True) 56 | # if not in win and not az - do nothing.. 57 | 58 | # just in case the last part of the last chr is in an az block 59 | if in_win: 60 | win.dump(output) 61 | -------------------------------------------------------------------------------- /rhocall/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import logging 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | 8 | def skip_variant(variant): 9 | """Check if a variant should be skipped 10 | 11 | Args: 12 | variant(cyvcf2.Variant) 13 | 14 | Returns: 15 | bool: if variant should be skipped 16 | """ 17 | # ignore low qual and indels for now 18 | if variant.FILTER: 19 | logger.debug("Filter %s" % variant.FILTER) 20 | return True 21 | 22 | if variant.end - variant.start > 1: 23 | logger.debug("Indel size %d" % (variant.end - variant.start)) 24 | return True 25 | 26 | return False 27 | 28 | 29 | def check_homozygote(variant, vcf, ind_index): 30 | """Check if a variant is homozygote 31 | 32 | Args: 33 | variant(cyvcf2.Variant) 34 | vcf(cyvcf2.VCF) 35 | ind_index(int) 36 | 37 | Returns: 38 | bool 39 | """ 40 | 41 | if variant.gt_types[ind_index] == vcf.HOM_REF: 42 | return True 43 | 44 | if variant.gt_types[ind_index] == vcf.HOM_ALT: 45 | return True 46 | 47 | return False 48 | 49 | 50 | def check_heterozygote(variant, vcf, ind_index): 51 | """Check if a variant is heterozygote 52 | 53 | Args: 54 | variant(cyvcf2.Variant) 55 | vcf(cyvcf2.VCF) 56 | ind_index(int) 57 | 58 | Returns: 59 | bool 60 | """ 61 | 62 | if variant.gt_types[ind_index] == vcf.HET: 63 | return True 64 | 65 | return False 66 | 67 | 68 | def check_block_end(nr_hets, nr_homs, constant, block_size, max_hets, max_het_fraction): 69 | """Check if the fraction of hets aborts the block""" 70 | 71 | if (nr_hets * constant / block_size) > max_hets: 72 | return True 73 | 74 | if (nr_hets / nr_homs) > max_het_fraction: 75 | return True 76 | 77 | return False 78 | 79 | 80 | def check_valid_block(block_size, shortest_block_tres, nr_homs, minimum_homs_tres): 81 | """Check if a block is of valid size 82 | 83 | Args: 84 | block_size(int): Size of block 85 | shortest_block_tres(int): User defined minimum block size 86 | nr_homs(int): Nr observed homozygotes in block 87 | minimum_homs_tres(int): User defined minimum homs for one block 88 | 89 | Returns: 90 | bool: If block is valid 91 | """ 92 | if block_size > shortest_block_tres: 93 | if nr_homs > minimum_homs_tres: 94 | return True 95 | 96 | return False 97 | -------------------------------------------------------------------------------- /rhocall/run_annotate_var.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from rhocall import __version__ 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | 7 | def run_annotate_var(proband_vcf, roh, quality_threshold, flag_upd_at_fraction, output): 8 | """Markup VCF file using rho-calls. VCF files annotated with GENMOD style 9 | inheritance patterns are accepted.""" 10 | 11 | az_info_header = { 12 | "ID": "AZ", 13 | "Number": 1, 14 | "Type": "Flag", 15 | "Source": "rhocall", 16 | "Version": __version__, 17 | "Description": "Autozygous positon call", 18 | } 19 | proband_vcf.add_info_to_header(az_info_header) 20 | 21 | hw_info_header = { 22 | "ID": "HW", 23 | "Number": 1, 24 | "Type": "Flag", 25 | "Source": "rhocall", 26 | "Version": __version__, 27 | "Description": "Hardy-Weinberg equilibrium (non-autozyous) positon call", 28 | } 29 | proband_vcf.add_info_to_header(hw_info_header) 30 | 31 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 32 | azqual_info_header = { 33 | "ID": "AZQUAL", 34 | "Number": 1, 35 | "Type": "String", 36 | "Source": "rhocall", 37 | "Version": __version__, 38 | "Description": "Autozygous positon call quality", 39 | } 40 | proband_vcf.add_info_to_header(azqual_info_header) 41 | 42 | aztype_info_header = { 43 | "ID": "AZTYPE", 44 | "Number": 1, 45 | "Type": "String", 46 | "Source": "rhocall", 47 | "Version": __version__, 48 | "Description": "Autozygous region type", 49 | } 50 | proband_vcf.add_info_to_header(aztype_info_header) 51 | 52 | output.write(proband_vcf.raw_header) 53 | var = next(proband_vcf) 54 | 55 | for r in roh: 56 | 57 | if r[0] == "#": 58 | continue 59 | 60 | col = r.rstrip().split("\t") 61 | chrom = str(col[0]) 62 | pos = int(col[1]) 63 | az = int(col[2]) 64 | qual = float(col[3]) 65 | # placeholder for future development: classify into UPD,SEX,DEL,IBD 66 | aztype = "ND" 67 | 68 | # print("looking for chrom %s %d" % (chrom, pos)) 69 | found_var = False 70 | new_var = True 71 | 72 | while not found_var: 73 | # print("testing var chrom %s %d" % (var.CHROM, var.start)) 74 | if var.CHROM == chrom and var.end == pos: 75 | found_var = True 76 | if az == 1: 77 | var.INFO["AZ"] = True 78 | else: 79 | var.INFO["HW"] = True 80 | 81 | var.INFO["AZQUAL"] = str(qual) 82 | var.INFO["AZTYPE"] = str(aztype) 83 | 84 | output.write(str(var)) 85 | new_var = True 86 | elif var.CHROM == chrom and var.start < pos: 87 | output.write(str(var)) 88 | new_var = True 89 | else: 90 | # not found, but passed the due position?! 91 | # fake finding variant, and pull new tsv (but not new var) 92 | logger.warning( 93 | "Variant given in rho-file was not found in variant file. " 94 | "Are you sure this is the sample you want to tag?" 95 | ) 96 | found_var = True 97 | new_var = False 98 | 99 | if new_var: 100 | var = next(proband_vcf) 101 | -------------------------------------------------------------------------------- /rhocall/run_annotate.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from rhocall import __version__ 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | 8 | def run_annotate(proband_vcf, bed, quality_threshold, flag_upd_at_fraction, output): 9 | """Markup VCF file using rho-call BED file.""" 10 | 11 | az_info_header = { 12 | "ID": "AZ", 13 | "Number": 1, 14 | "Type": "Flag", 15 | "Source": "rhocall", 16 | "Version": __version__, 17 | "Description": "Autozygous positon call", 18 | } 19 | proband_vcf.add_info_to_header(az_info_header) 20 | 21 | hw_info_header = { 22 | "ID": "HW", 23 | "Number": 1, 24 | "Type": "Flag", 25 | "Source": "rhocall", 26 | "Version": __version__, 27 | "Description": "Hardy-Weinberg equilibrium (non-autozyous) positon call", 28 | } 29 | proband_vcf.add_info_to_header(hw_info_header) 30 | 31 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 32 | azqual_info_header = { 33 | "ID": "AZQUAL", 34 | "Number": 1, 35 | "Type": "String", 36 | "Source": "rhocall", 37 | "Version": __version__, 38 | "Description": "Autozygous positon call quality", 39 | } 40 | proband_vcf.add_info_to_header(azqual_info_header) 41 | 42 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 43 | azlength_info_header = { 44 | "ID": "AZLENGTH", 45 | "Number": 1, 46 | "Type": "String", 47 | "Source": "rhocall", 48 | "Version": __version__, 49 | "Description": "Autozygous region length", 50 | } 51 | proband_vcf.add_info_to_header(azlength_info_header) 52 | 53 | aztype_info_header = { 54 | "ID": "AZTYPE", 55 | "Number": 1, 56 | "Type": "String", 57 | "Source": "rhocall", 58 | "Version": __version__, 59 | "Description": "Autozygous region type", 60 | } 61 | proband_vcf.add_info_to_header(aztype_info_header) 62 | 63 | output.write(proband_vcf.raw_header) 64 | 65 | var = next(proband_vcf, False) 66 | 67 | found_any_var = False 68 | 69 | for r in bed: 70 | 71 | if r[0] == "#": 72 | continue 73 | 74 | col = r.rstrip().split("\t") 75 | chrom = str(col[0]) 76 | start = int(col[1]) 77 | end = int(col[2]) 78 | az = int(col[3]) 79 | qual = float(col[4]) 80 | # placeholder for future development: classify into UPD,SEX,DEL,IBD 81 | aztype = "ND" 82 | azlength = end - start + 1 83 | 84 | found_var = False 85 | 86 | logger.debug("looking for bed window %s %d-%d az %d" % (chrom, start, end, az)) 87 | 88 | passed_win = False 89 | 90 | while var and not passed_win: 91 | # print("testing var chrom %s %d" % (var.CHROM, var.start)) 92 | if var.CHROM == chrom and var.end >= start and var.end <= end: 93 | # variant in window - print, and go to next var 94 | if az == 1: 95 | var.INFO["AZ"] = True 96 | else: 97 | var.INFO["HW"] = True 98 | 99 | var.INFO["AZQUAL"] = str(qual) 100 | var.INFO["AZLENGTH"] = str(azlength) 101 | var.INFO["AZTYPE"] = str(aztype) 102 | found_var = True 103 | 104 | output.write(str(var)) 105 | var = next(proband_vcf, False) 106 | 107 | elif var.CHROM == chrom and var.start < start: 108 | # before next win (and on same chr) - write and pull new var 109 | output.write(str(var)) 110 | var = next(proband_vcf, False) 111 | 112 | elif var.CHROM == chrom and var.end > end: 113 | # var is after last window position, same chr 114 | # pull new window, but no new variant and don't write var yet 115 | passed_win = True 116 | # when written? 117 | elif var.CHROM != chrom: 118 | # first time around, assume there are many variants, at least one 119 | # per bed interval. 120 | 121 | if found_var: 122 | # then we either just exited win by drawing var from new chr 123 | # so pull next win, without deciding the fate of this var yet 124 | passed_win = True 125 | else: 126 | # or window is on new chr, and we need to draw new vars to 127 | # get there - essentially "before next win" 128 | output.write(str(var)) 129 | var = next(proband_vcf, False) 130 | 131 | else: 132 | # not found, but passed the due position?! 133 | # var = next(proband_vcf) 134 | logger.error("Oops? Unexpected window/variant set!") 135 | 136 | # out of windows. print any remaining unflagged vars. 137 | while var: 138 | output.write(str(var)) 139 | var = next(proband_vcf, False) 140 | 141 | if not found_any_var: 142 | logger.warning( 143 | "No variants found for at least one window." 144 | " - were correctly matched files used for annotation?" 145 | ) 146 | -------------------------------------------------------------------------------- /rhocall/run_viz.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import numpy 3 | import os 4 | import matplotlib.mlab as mlab 5 | import matplotlib.pyplot as plt 6 | import math 7 | import sys 8 | 9 | 10 | # compute the ratio of homozygous snps across the genome 11 | def generate_bins(input_vcf, window, filter, mnv, minqual, rsid, minaf, aftag, maxaf, minsnv): 12 | bins = {} 13 | contigs = {} 14 | # collect the number of hetrozygous and homozygous snps for each bin 15 | for line in input_vcf: 16 | if line[0] == "#": 17 | if "##contig=")[0]) 20 | contigs[contig_id] = contig_len 21 | # sys.stderr.write("DEBUG: contig id %s len %i\n"%(contig_id, contig_len)) 22 | 23 | if "#CHROM" in line: 24 | for contig in contigs: 25 | bins[contig] = numpy.zeros((int(math.ceil(contigs[contig] / float(window))), 2)) 26 | continue 27 | if filter and not "\tPASS\t" in line: 28 | continue 29 | 30 | content = line.strip().split() 31 | # skip mnv calls 32 | if not mnv: 33 | if len(content[3]) != 1 or len(content[4]) != 1: 34 | continue 35 | 36 | # filter low quality variants 37 | ok = True 38 | try: 39 | quality = float(content[5]) 40 | if quality < minqual: 41 | ok = False 42 | except: 43 | pass 44 | if not ok: 45 | continue 46 | 47 | # rrsid filter(if enabled) 48 | if rsid and not content[2].startswith("rs"): 49 | # sys.stderr.write("DEBUG: drop non rsID variant.") 50 | continue 51 | 52 | # allele frequency filter 53 | if minaf: 54 | if ";{}=".format(aftag) in content[7]: 55 | try: 56 | af = float(content[7].split(";{}=".format(aftag))[-1].split(";")[0]) 57 | if af < minaf or af > maxaf: 58 | continue 59 | except: 60 | print("Error parsing allele frequency.") 61 | continue 62 | else: 63 | continue 64 | 65 | pos = int(math.floor(int(content[1]) / float(window))) 66 | if "1/1" in content[-1] or "0/0" in content[-1] or "1|1" in content[-1]: 67 | bins[content[0]][pos][1] += 1 68 | elif "./." in content[-1] or "./1" in content[-1]: 69 | pass 70 | else: 71 | bins[content[0]][pos][0] += 1 72 | 73 | # compute ratios 74 | for chromosome in bins: 75 | chrom_bins = bins[chromosome] 76 | nr_snps = chrom_bins[:,0] + chrom_bins[:,1] 77 | bins[chromosome] = numpy.where(nr_snps < minsnv, "NaN", chrom_bins[:,1] / nr_snps) 78 | return bins 79 | 80 | 81 | # take the rhocall output and find all reported ROH 82 | def extract_roh(rho): 83 | roh = {} 84 | 85 | for line in rho: 86 | if line[0] == "#": 87 | continue 88 | elif "CHROMOSOME_TOT" in line: 89 | continue 90 | 91 | if line[0] + line[1] == "RG": 92 | content = line.strip().split() 93 | if not content[2] in roh: 94 | # New chromosome 95 | roh[content[2]] = [] 96 | # Mark start and end 97 | roh[content[2]].append([int(content[3]), int(content[4])]) 98 | return roh 99 | 100 | 101 | # create the plots, one for each chromosome, and print them to the assigned directory 102 | def generate_plots(binned_zygosity, roh, window, pointsize, out_dir): 103 | for chromosome in binned_zygosity: 104 | if "GL" in chromosome: 105 | continue 106 | 107 | posvector = numpy.array(range(0, len(binned_zygosity[chromosome]))) * window / 1000.0 108 | 109 | plt.figure(1) 110 | plt.subplot(111) 111 | 112 | fraction = plt.scatter( 113 | posvector, 114 | binned_zygosity[chromosome], 115 | c="black", 116 | s=pointsize, 117 | alpha=0.5, 118 | marker="o", 119 | label="fraction", 120 | ) 121 | median_fraction = numpy.median( 122 | binned_zygosity[chromosome][numpy.where(binned_zygosity[chromosome] > -1)] 123 | ) 124 | (median,) = plt.plot( 125 | [0, max(posvector)], 126 | [median_fraction, median_fraction], 127 | linewidth=4, 128 | color="green", 129 | alpha=0.75, 130 | label="median fraction", 131 | ) 132 | (ROH,) = plt.plot([0, 0], [-1, -1], linewidth=2, color="red", label="RHO") 133 | 134 | plt.legend([median, fraction, ROH], ["median fraction", "Fraction", "RHO"]) 135 | if chromosome in roh: 136 | 137 | roh[chromosome] = numpy.array(roh[chromosome]) / 1000 138 | for r in roh[chromosome]: 139 | ycoord = [1.1, 1.1] 140 | plt.plot([r[0], r[1]], ycoord, linewidth=4, color="red") 141 | # plt.ylim(ymax = 3*median_coverage, ymin = 0) 142 | plt.title("RHO plot on chromosome {}".format(chromosome)) 143 | 144 | plt.ylim(ymin=0) 145 | plt.ylim(ymax=1.2) 146 | plt.xlabel("Positions(Kb)") 147 | plt.ylabel("Fraction of homozygous snps") 148 | figure = plt.gcf() 149 | figure.set_size_inches(16, 10) 150 | plt.savefig("{}/{}.png".format(out_dir, chromosome), dpi=100) 151 | plt.close() 152 | 153 | 154 | # create the plots, one for each chromosome, and print them to the assigned directory 155 | def generate_wig(binned_zygosity, roh, window, outfile_basename): 156 | 157 | wigf = open(outfile_basename + ".wig", "w") 158 | wigf.write('track type=wiggle_0 description="Fraction of homozygous snps"\n') 159 | 160 | bedf = open(outfile_basename + ".bed", "w") 161 | bedf.write('track name=rhocall description="Regions of autozygosity"\n') 162 | for chromosome in binned_zygosity: 163 | if "GL" in chromosome: 164 | continue 165 | 166 | # IGV range 0-1, mid 0 works fine. 167 | wigf.write("fixedStep chrom=%s start=1 step=%i\n" % (chromosome, window)) 168 | for z in binned_zygosity[chromosome]: 169 | wigf.write("{}\n".format(z)) 170 | 171 | if chromosome in roh: 172 | for r in roh[chromosome]: 173 | bedf.write("{}\t{}\t{}\n".format(chromosome, r[0], r[1])) 174 | -------------------------------------------------------------------------------- /rhocall/run_annotate_bcfroh.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from rhocall import __version__ 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | 8 | def run_annotate_rg(proband_vcf, bcfroh, quality_threshold, flag_upd_at_fraction, output, select_sample): 9 | """Markup VCF file using rho-call BED file. 10 | 11 | If a select_sample is given, only ROH entries for that sample is processed. Otherwise the entries for the 12 | first sample encountered is used, even if more are present in the bcftools ROH RG file. 13 | """ 14 | 15 | az_info_header = { 16 | "ID": "AZ", 17 | "Number": 0, 18 | "Type": "Flag", 19 | "Source": "rhocall", 20 | "Version": __version__, 21 | "Description": "Autozygous positon call", 22 | } 23 | proband_vcf.add_info_to_header(az_info_header) 24 | 25 | hw_info_header = { 26 | "ID": "HW", 27 | "Number": 0, 28 | "Type": "Flag", 29 | "Source": "rhocall", 30 | "Version": __version__, 31 | "Description": "Hardy-Weinberg equilibrium (non-autozyous) positon call", 32 | } 33 | proband_vcf.add_info_to_header(hw_info_header) 34 | 35 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 36 | azqual_info_header = { 37 | "ID": "AZQUAL", 38 | "Number": 1, 39 | "Type": "String", 40 | "Source": "rhocall", 41 | "Version": __version__, 42 | "Description": "Autozygous positon call quality", 43 | } 44 | proband_vcf.add_info_to_header(azqual_info_header) 45 | 46 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 47 | azlength_info_header = { 48 | "ID": "AZLENGTH", 49 | "Number": 1, 50 | "Type": "String", 51 | "Source": "rhocall", 52 | "Version": __version__, 53 | "Description": "Autozygous region length", 54 | } 55 | proband_vcf.add_info_to_header(azlength_info_header) 56 | 57 | # pyvcf2 does not seem to play with floats yet. Setting type to string for now. 58 | azlength_info_header = { 59 | "ID": "AZMARKERS", 60 | "Number": 1, 61 | "Type": "String", 62 | "Source": "rhocall", 63 | "Version": __version__, 64 | "Description": "Autozygous region length", 65 | } 66 | proband_vcf.add_info_to_header(azlength_info_header) 67 | 68 | aztype_info_header = { 69 | "ID": "AZTYPE", 70 | "Number": 1, 71 | "Type": "String", 72 | "Source": "rhocall", 73 | "Version": __version__, 74 | "Description": "Autozygous region type", 75 | } 76 | proband_vcf.add_info_to_header(aztype_info_header) 77 | 78 | output.write(proband_vcf.raw_header) 79 | 80 | var = next(proband_vcf, False) 81 | 82 | found_any_var = False 83 | 84 | for r in bcfroh: 85 | 86 | if r[0] == "#": 87 | continue 88 | 89 | col = r.rstrip().split("\t") 90 | if col[0] != "RG": 91 | continue 92 | 93 | # trust RG entries 94 | if col[0] == "RG": 95 | 96 | sample = str(col[1]) 97 | if select_sample and sample != select_sample: 98 | continue 99 | if not select_sample: 100 | select_sample = sample 101 | chrom = str(col[2]) 102 | start = int(col[3]) 103 | end = int(col[4]) 104 | azlength = int(col[5]) 105 | nmarkers = int(col[6]) 106 | qual = float(col[7]) 107 | 108 | found_var = False 109 | 110 | # placeholder for future development: classify into UPD,SEX,DEL,IBD 111 | aztype = "ND" 112 | azlength = end - start + 1 113 | 114 | logger.debug( 115 | "looking for roh window %s %d-%d nmarkers %d qual %f" 116 | % (chrom, start, end, nmarkers, qual) 117 | ) 118 | 119 | passed_win = False 120 | 121 | while var and not passed_win: 122 | # print("testing var chrom %s %d" % (var.CHROM, var.start)) 123 | if var.CHROM == chrom and var.end >= start and var.end <= end: 124 | # variant in window - print, and go to next var 125 | var.INFO["AZ"] = True 126 | var.INFO["AZQUAL"] = str(qual) 127 | var.INFO["AZLENGTH"] = str(azlength) 128 | var.INFO["AZMARKERS"] = str(nmarkers) 129 | var.INFO["AZTYPE"] = str(aztype) 130 | found_var = True 131 | found_any_var = True 132 | 133 | output.write(str(var)) 134 | var = next(proband_vcf, False) 135 | 136 | elif var.CHROM == chrom and var.start < start: 137 | # before next win (and on same chr) - write and pull new var 138 | output.write(str(var)) 139 | var = next(proband_vcf, False) 140 | 141 | elif var.CHROM == chrom and var.end > end: 142 | # var is after last window position, same chr 143 | # pull new window, but no new variant and don't write var yet 144 | passed_win = True 145 | # when written? 146 | elif var.CHROM != chrom: 147 | # first time around, assume there are many variants, at least one 148 | # per bed interval. 149 | 150 | if found_var: 151 | # then we either just exited win by drawing var from new chr 152 | # so pull next win, without deciding the fate of this var yet 153 | passed_win = True 154 | else: 155 | # or window is on new chr, and we need to draw new vars to 156 | # get there - essentially "before next win" 157 | output.write(str(var)) 158 | logger.debug( 159 | "Win chr %s not same as var chr %s: keep drawing new vars (end %s)." 160 | % (chrom, var.CHROM, var.end) 161 | ) 162 | var = next(proband_vcf, False) 163 | 164 | else: 165 | # not found, but passed the due position?! 166 | # var = next(proband_vcf) 167 | logger.error("Oops? Unexpected window/variant set!") 168 | 169 | # out of windows. print any remaining unflagged vars. 170 | while var: 171 | output.write(str(var)) 172 | var = next(proband_vcf, False) 173 | 174 | if not found_any_var: 175 | logger.warning( 176 | "No variants found for at least one window." 177 | " - were correctly matched files used for annotation?" 178 | ) 179 | -------------------------------------------------------------------------------- /rhoviz.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import numpy 3 | import os 4 | import matplotlib.mlab as mlab 5 | import matplotlib.pyplot as plt 6 | import math 7 | 8 | version = "42" 9 | 10 | 11 | # compute the ratio of homozygous snps across the genome 12 | def generate_bins(args): 13 | bins = {} 14 | contigs = {} 15 | # collect the number of hetrozygous and homozygous snps for each bin 16 | for line in open(args.input_vcf): 17 | if line[0] == "#": 18 | if "##contig= args.maxaf: 59 | continue 60 | except: 61 | print("Error parsing allele frequency.") 62 | continue 63 | else: 64 | continue 65 | 66 | pos = int(math.floor(int(content[1]) / float(args.window))) 67 | if "1/1" in content[-1] or "0/0" in content[-1] or "1|1" in content[-1]: 68 | bins[content[0]][pos][1] += 1 69 | elif "./." in content[-1] or "./1" in content[-1]: 70 | pass 71 | else: 72 | bins[content[0]][pos][0] += 1 73 | 74 | # compute ratios 75 | for chromosome in bins: 76 | tmp_ratios = [] 77 | for window in bins[chromosome]: 78 | if sum(window) < args.minsnv: 79 | tmp_ratios.append(-1) 80 | else: 81 | tmp_ratios.append(window[1] / float(window[1] + window[0])) 82 | bins[chromosome] = numpy.array(tmp_ratios) 83 | return bins 84 | 85 | 86 | # take the rhocall output and find all reported ROH 87 | def extract_roh(args): 88 | roh = {} 89 | chrom_tot = {} 90 | for line in open(args.rho): 91 | if line[0] == "#": 92 | continue 93 | elif "CHROMOSOME_TOT" in line: 94 | continue 95 | 96 | content = line.strip().split() 97 | if not content[0] in roh: 98 | roh[content[0]] = [] 99 | roh[content[0]].append([int(content[1]), int(content[2])]) 100 | 101 | return (roh, chrom_tot) 102 | 103 | 104 | # create the plots, one for each chromosome, and print them to the assigned directory 105 | def generate_plots(binned_zygosity, roh, chrom_tot, args): 106 | for chromosome in binned_zygosity: 107 | if "GL" in chromosome: 108 | continue 109 | 110 | posvector = numpy.array(range(0, len(binned_zygosity[chromosome]))) * args.window / 1000.0 111 | 112 | plt.figure(1) 113 | plt.subplot(111) 114 | 115 | fraction = plt.scatter( 116 | posvector, 117 | binned_zygosity[chromosome], 118 | c="black", 119 | s=args.pointsize, 120 | alpha=0.5, 121 | marker="o", 122 | label="fraction", 123 | ) 124 | median_fraction = numpy.median( 125 | binned_zygosity[chromosome][numpy.where(binned_zygosity[chromosome] > -1)] 126 | ) 127 | (median,) = plt.plot( 128 | [0, max(posvector)], 129 | [median_fraction, median_fraction], 130 | linewidth=4, 131 | color="green", 132 | alpha=0.75, 133 | label="median fraction", 134 | ) 135 | (ROH,) = plt.plot([0, 0], [-1, -1], linewidth=2, color="red", label="RHO") 136 | 137 | plt.legend([median, fraction, ROH], ["median fraction", "Fraction", "RHO"]) 138 | if chromosome in roh: 139 | 140 | roh[chromosome] = numpy.array(roh[chromosome]) / 1000 141 | for r in roh[chromosome]: 142 | ycoord = [1.1, 1.1] 143 | plt.plot([r[0], r[1]], ycoord, linewidth=4, color="red") 144 | # plt.ylim(ymax = 3*median_coverage, ymin = 0) 145 | plt.title("RHO plot on chromosome {}".format(chromosome)) 146 | 147 | plt.ylim(ymin=0) 148 | plt.ylim(ymax=1.2) 149 | plt.xlabel("Positions(Kb)") 150 | plt.ylabel("Fraction of homozygous snps") 151 | figure = plt.gcf() 152 | figure.set_size_inches(16, 10) 153 | plt.savefig("{}/{}.png".format(args.dir, chromosome), dpi=100) 154 | plt.close() 155 | 156 | 157 | def main(args): 158 | os.system("mkdir {}".format(args.dir)) 159 | binned_zygosity = generate_bins(args) 160 | roh, chrom_tot = extract_roh(args) 161 | generate_plots(binned_zygosity, roh, chrom_tot, args) 162 | 163 | 164 | ## Argument parsing 165 | parser = argparse.ArgumentParser(description="Call runs of autozygosity.") 166 | parser.add_argument("--input_vcf", "-i", type=str, required=True, help="Input (sorted) vcf file") 167 | parser.add_argument( 168 | "--dir", 169 | "-d", 170 | type=str, 171 | required=True, 172 | help="output directory, the files will be named dir/chr.png, one picture is printed per chromosome", 173 | ) 174 | parser.add_argument( 175 | "--rho", "-r", type=str, required=True, help="Input RHO file produced from rhocall" 176 | ) 177 | parser.add_argument("--window", "-w", type=int, default=10000, help="window size(bases)") 178 | parser.add_argument( 179 | "--minsnv", "-m", type=int, default=2, help="minimum number of snvs for each plotted bin" 180 | ) 181 | parser.add_argument( 182 | "--maxsnv", "-M", type=int, default=20, help="maximum number of snvs for each plotted bin" 183 | ) 184 | parser.add_argument( 185 | "--minaf", 186 | type=float, 187 | default=0.1, 188 | help="minimum allele frequency(this variable must be set to 0 if the allele frequency is not annotated)", 189 | ) 190 | parser.add_argument("--maxaf", type=float, default=0.9, help="maximum allele frequency") 191 | parser.add_argument("--mnv", action="store_true", help="include MNV") 192 | parser.add_argument("--aftag", type=str, default="1000GAF", help="the allele frequency tag") 193 | parser.add_argument( 194 | "--minqual", 195 | "-q", 196 | type=int, 197 | default=100, 198 | help="do not add snvs to a bin if there quality is less than this value", 199 | ) 200 | parser.add_argument("--pointsize", "-p", type=int, default=8, help="Size of the points (pixels)") 201 | parser.add_argument( 202 | "--rsid", "-s", action="store_true", help="Skip variants not containing an rsid" 203 | ) 204 | parser.add_argument( 205 | "--nofilter", 206 | "-n", 207 | action="store_true", 208 | help="include variants, even if they are not labeled PASS", 209 | ) 210 | args = parser.parse_args() 211 | 212 | main(args) 213 | -------------------------------------------------------------------------------- /rhocall/run_rho.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from .prints import end_block, end_chr 4 | from .utils import ( 5 | skip_variant, 6 | check_homozygote, 7 | check_heterozygote, 8 | check_block_end, 9 | check_valid_block, 10 | ) 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def run_rhocall( 16 | ctx, 17 | proband_vcf, 18 | block_constant, 19 | max_hets, 20 | max_het_fraction, 21 | minimum_homs, 22 | shortest_block, 23 | flag_UPD_at_fraction, 24 | individual, 25 | ): 26 | """docstring for run_rho_call""" 27 | block_constant = 1000000 28 | # block parameters 29 | hom_block_start = None 30 | current_chr = None 31 | hom_block_end = None 32 | current_block_hets = 0 33 | current_block_homs = 0 34 | 35 | # chromosome parameters 36 | chr_blocked = 0 37 | chr_homs = 0 38 | chr_hets = 0 39 | chr_last_pos_seen = None 40 | 41 | # state variables for parser 42 | seen_hom = False 43 | block_ends = False 44 | start_new_block = False 45 | chr_ends = False 46 | 47 | for var in proband_vcf: 48 | 49 | if not skip_variant(var): 50 | # new block if new chr 51 | if current_chr != None and var.CHROM != current_chr: 52 | block_ends = True 53 | chr_ends = True 54 | start_new_block = True 55 | logger.debug("Leaving chromosome %s for %s." % (current_chr, var.CHROM)) 56 | 57 | elif seen_hom == False: 58 | logger.debug(type(var.gt_types)) 59 | logger.debug(len(var.gt_types)) 60 | logger.debug("%s %d" % (var.CHROM, var.start)) 61 | 62 | if check_homozygote(var, proband_vcf, individual): 63 | # found homozygous variant 64 | start_new_block = True 65 | logger.debug("Start new block.") 66 | 67 | elif seen_hom == True: 68 | if check_heterozygote(var, proband_vcf, individual): 69 | # update nr of hets. Tempting to leave the het count/block end at last hom? 70 | current_block_hets += 1 71 | hom_block_end = var.end 72 | if var.end > hom_block_start: 73 | hom_block_end = var.end 74 | elif chr_last_pos_seen > hom_block_start: 75 | hom_block_end = chr_last_pos_seen 76 | else: 77 | logger.error("Block size negative!") 78 | # Raise exception?? 79 | 80 | block_size = hom_block_end - hom_block_start + 1 81 | 82 | logger.debug( 83 | "hets: %d homs: %d block_size: %d" 84 | % (current_block_hets, current_block_homs, block_size) 85 | ) 86 | 87 | block_ends = check_block_end( 88 | nr_hets=current_block_hets, 89 | nr_homs=current_block_homs, 90 | constant=block_constant, 91 | block_size=block_size, 92 | max_hets=max_hets, 93 | max_het_fraction=max_het_fraction, 94 | ) 95 | if block_ends: 96 | logger.debug( 97 | "Leaving block with %d hets and block" 98 | " size %d." % (current_block_hets, block_size) 99 | ) 100 | 101 | elif check_homozygote(var, proband_vcf, individual): 102 | current_block_homs += 1 103 | current_block_end = var.end 104 | 105 | if block_ends: 106 | if hom_block_start != None: 107 | 108 | if var.end > hom_block_start: 109 | hom_block_end = var.end 110 | elif chr_last_pos_seen > hom_block_start: 111 | hom_block_end = chr_last_pos_seen 112 | else: 113 | logger.error("Block size negative!") 114 | # Raise exception?? 115 | 116 | # Nb - chr end/start! 117 | block_size = hom_block_end - hom_block_start + 1 118 | 119 | block_ends = check_block_end( 120 | nr_hets=current_block_hets, 121 | nr_homs=current_block_homs, 122 | constant=block_constant, 123 | block_size=block_size, 124 | max_hets=max_hets, 125 | max_het_fraction=max_het_fraction, 126 | ) 127 | 128 | if block_ends: 129 | valid_block = check_valid_block( 130 | block_size=block_size, 131 | shortest_block_tres=shortest_block, 132 | nr_homs=current_block_homs, 133 | minimum_homs_tres=minimum_homs, 134 | ) 135 | if valid_block: 136 | end_block( 137 | current_chr, 138 | hom_block_start, 139 | hom_block_end, 140 | current_block_hets, 141 | current_block_homs, 142 | ) 143 | 144 | chr_blocked += block_size 145 | 146 | current_block_homs = 0 147 | current_block_hets = 0 148 | hom_block_start = None 149 | hom_block_end = None 150 | seen_hom = False 151 | 152 | else: 153 | logger.info( 154 | "Block ends before one was started at %s %d." % (var.CHROM, var.start) 155 | ) 156 | 157 | block_ends = False 158 | 159 | if chr_ends: 160 | chr_size_spanned = chr_last_pos_seen 161 | end_chr( 162 | current_chr, 163 | chr_size_spanned, 164 | chr_blocked, 165 | chr_hets, 166 | chr_homs, 167 | flag_UPD_at_fraction, 168 | ) 169 | 170 | chr_homs = 0 171 | chr_hets = 0 172 | current_chr = var.CHROM 173 | chr_blocked = 0 174 | chr_ends = False 175 | 176 | if start_new_block: 177 | # new block; double check homoz for new chr.. just ignore if het. 178 | if check_homozygote(var, proband_vcf, individual): 179 | seen_hom = True 180 | current_block_homs = 1 181 | hom_block_start = var.start 182 | hom_block_end = var.end 183 | current_chr = var.CHROM 184 | 185 | start_new_block = False 186 | 187 | # finally, update chr totals and then return to beginning of loop to draw new var 188 | if check_homozygote(var, proband_vcf, individual): 189 | chr_homs += 1 190 | elif check_heterozygote(var, proband_vcf, individual): 191 | chr_hets += 1 192 | 193 | chr_last_pos_seen = var.end 194 | 195 | if hom_block_end and hom_block_start: 196 | # and check for block once more after seeing last var 197 | block_size = hom_block_end - hom_block_start + 1 198 | block_ends = check_block_end( 199 | nr_hets=current_block_hets, 200 | nr_homs=current_block_homs, 201 | constant=block_constant, 202 | block_size=block_size, 203 | max_hets=max_hets, 204 | max_het_fraction=max_het_fraction, 205 | ) 206 | 207 | if block_ends: 208 | valid_block = check_valid_block( 209 | block_size=block_size, 210 | shortest_block_tresh=shortest_block, 211 | nr_homs=current_block_homs, 212 | minimum_homs_tres=minimum_homs, 213 | ) 214 | 215 | if valid_block: 216 | end_block( 217 | current_chr, hom_block_start, hom_block_end, current_block_hets, block_homs 218 | ) 219 | -------------------------------------------------------------------------------- /rhocall.py: -------------------------------------------------------------------------------- 1 | from cyvcf2 import * 2 | import argparse 3 | import numpy as np 4 | 5 | version = "0.1" 6 | 7 | ### Argument parsing 8 | 9 | parser = argparse.ArgumentParser(description='Call runs of autozygosity.') 10 | parser.add_argument('--input_vcf','-i', type=str, 11 | required=True, help='Input (sorted) vcf file') 12 | parser.add_argument('--max_hets', '-m', type=float, default=2, 13 | help='Max heterozygotes per Mb in a homozygous block') 14 | parser.add_argument('--max_het_fraction', '-f', type=float, default=2, 15 | help='Max heterozygotes over homozygotes fraction in a homozygous block') 16 | # 4.8 might be a normal fraction 17 | 18 | parser.add_argument('--minimum_homs', '-n', type=int, default = 5, 19 | help='Minimum absolute number of homozygotes to report a block') 20 | parser.add_argument('--shortest_block', '-s', type=int, default=100000, 21 | help='Shortest block') 22 | parser.add_argument('--flag_UPD_at_fraction', '-u', type=float, default=0.3, 23 | help='Flag UPD if homozygous blocks span this fraction of total chr size') 24 | parser.add_argument('--individual','-k', type=int, default=0, 25 | help='Index of individual in vcf/bcf, 0-based.') 26 | parser.add_argument('--DEBUG', help='Enable debug output.', action='store_true') 27 | 28 | args = parser.parse_args() 29 | 30 | ### Output format functions 31 | 32 | def output_bed_header(): 33 | print "#rhocall version %s" % (version) 34 | 35 | def end_block(block_chr, block_start, block_end, block_hets, block_homs): 36 | print "%s\t%d\t%d\t%d\t%d\t%d" % ( block_chr, block_start, block_end, block_end-block_start+1, block_hets, block_homs ) 37 | 38 | def end_chr(current_chr, chr_size_spanned, chr_blocked, chr_hets, chr_homs): 39 | flag = "Normal" 40 | 41 | if chr_blocked / chr_size_spanned > args.flag_UPD_at_fraction: 42 | if current_chr == "X" or current_chr == "chrX": 43 | flag = "HemiX" 44 | elif current_chr == "Y" or current_chr == "chrY": 45 | flag = "HemiY" 46 | elif current_chr == "MT" or current_chr == "chrMT" or current_chr == "M" or current_chr == "chrM": 47 | flag = "HemiMT" 48 | else: 49 | flag = "UPD" 50 | else: 51 | if current_chr == "X" or current_chr == "chrX": 52 | flag = "HetX" 53 | elif current_chr == "Y" or current_chr == "chrY": 54 | if chr_hets + chr_homs < 1000: 55 | flag = "NoY" 56 | 57 | flag = "HetY" 58 | elif current_chr == "MT" or current_chr == "chrMT" or current_chr == "M" or current_chr == "chrM": 59 | flag = "HetMT" 60 | 61 | print "%s\t1\t%d\tCHROMOSOME_TOTAL\t%d\t%d\t%d\t%s" % (current_chr, chr_size_spanned, chr_blocked, chr_hets, chr_homs, flag) 62 | 63 | ### Open vcf file 64 | # assuming a sorted vcf - check needed? 65 | proband_vcf = VCF(args.input_vcf) 66 | 67 | # start off output stream 68 | output_bed_header() 69 | 70 | # block parameters 71 | hom_block_start = None 72 | current_chr = None 73 | hom_block_end = None 74 | current_block_hets = 0 75 | current_block_homs = 0 76 | 77 | #chromosome parameters 78 | chr_blocked = 0 79 | chr_homs = 0 80 | chr_hets = 0 81 | chr_last_pos_seen = None 82 | 83 | # state variables for parser 84 | seen_hom = False 85 | block_ends = False 86 | start_new_block = False 87 | chr_ends = False 88 | 89 | for var in proband_vcf: 90 | 91 | # ignore low qual and indels for now 92 | if var.FILTER: 93 | if args.DEBUG: 94 | print "Filter %s" % var.FILTER 95 | continue 96 | 97 | if var.end - var.start > 1: 98 | if args.DEBUG: 99 | print "Indel size %d" % (var.end - var.start) 100 | continue 101 | 102 | # new block if new chr 103 | if current_chr != None and var.CHROM != current_chr: 104 | block_ends = True 105 | chr_ends = True 106 | start_new_block = True 107 | if args.DEBUG: 108 | print "Leaving chromosome %s for %s." % ( current_chr, var.CHROM ) 109 | elif seen_hom == False: 110 | if args.DEBUG: 111 | print type(var.gt_types) 112 | print len(var.gt_types) 113 | # cpy = np.array(var.gt_bases) 114 | # print "%d" % cpy.ndim 115 | print "%s %d" % (var.CHROM, var.start) 116 | 117 | if var.gt_types[args.individual] == proband_vcf.HOM_REF or var.gt_types[args.individual] == proband_vcf.HOM_ALT: 118 | # found homozygous variant 119 | start_new_block = True 120 | if args.DEBUG: 121 | print "Start new block." 122 | 123 | elif seen_hom == True: 124 | if var.gt_types[args.individual] == proband_vcf.HET: 125 | if var.gt_types[args.individual] == proband_vcf.HET: 126 | # update nr of hets. Tempting to leave the het count/block end at last hom? 127 | current_block_hets += 1 128 | hom_block_end = var.end 129 | if var.end > hom_block_start: 130 | hom_block_end = var.end 131 | elif chr_last_pos_seen > hom_block_start: 132 | hom_block_end = chr_last_pos_seen 133 | else: 134 | print "ERROR - block size negative!" 135 | 136 | block_size = hom_block_end - hom_block_start + 1 137 | 138 | if args.DEBUG: 139 | print "hets: %d homs: %d block_size: %d" % (current_block_hets, current_block_homs, block_size) 140 | if ( (current_block_hets) * 1000000 / block_size > args.max_hets ) or (current_block_hets) /current_block_homs > args.max_het_fraction : 141 | block_ends = True 142 | if args.DEBUG: 143 | print "Leaving block with %d hets and block size %d." % ( current_block_hets, block_size ) 144 | 145 | elif var.gt_types[args.individual] == proband_vcf.HOM_REF or var.gt_types[args.individual] == proband_vcf.HOM_ALT: 146 | current_block_homs += 1 147 | current_block_end = var.end 148 | 149 | if block_ends: 150 | if hom_block_start != None: 151 | 152 | if var.end > hom_block_start: 153 | hom_block_end = var.end 154 | elif chr_last_pos_seen > hom_block_start: 155 | hom_block_end = chr_last_pos_seen 156 | else: 157 | print "ERROR - block size negative!" 158 | 159 | # Nb - chr end/start! 160 | block_size = hom_block_end - hom_block_start + 1 161 | 162 | if current_block_hets * 1000000 / block_size > args.max_hets or current_block_hets / current_block_homs > args.max_het_fraction : 163 | if block_size > args.shortest_block and current_block_homs > args.minimum_homs: 164 | end_block(current_chr, hom_block_start, hom_block_end, current_block_hets, current_block_homs) 165 | 166 | chr_blocked += block_size 167 | 168 | current_block_homs = 0 169 | current_block_hets = 0 170 | hom_block_start = None 171 | hom_block_end = None 172 | seen_hom = False 173 | 174 | else: 175 | if args.DEBUG: 176 | print "Block ends before one was started at %s %d." % (var.CHROM, var.start) 177 | 178 | block_ends = False 179 | 180 | if chr_ends: 181 | chr_size_spanned = chr_last_pos_seen 182 | end_chr(current_chr, chr_size_spanned, chr_blocked, chr_hets, chr_homs) 183 | 184 | chr_homs = 0 185 | chr_hets = 0 186 | current_chr = var.CHROM 187 | chr_blocked = 0 188 | chr_ends = False 189 | 190 | if start_new_block: 191 | # new block; double check homoz for new chr.. just ignore if het. 192 | if var.gt_types[args.individual] == 0 or var.gt_types[args.individual] == 3: 193 | seen_hom = True 194 | current_block_homs = 1 195 | hom_block_start = var.start 196 | hom_block_end = var.end 197 | current_chr = var.CHROM 198 | 199 | start_new_block = False 200 | 201 | # finally, update chr totals and then return to beginning of loop to draw new var 202 | if var.gt_types[args.individual] == proband_vcf.HOM_REF or var.gt_types[args.individual] == proband_vcf.HOM_ALT: 203 | chr_homs += 1 204 | elif var.gt_types[args.individual] == proband_vcf.HET: 205 | chr_hets += 1 206 | 207 | chr_last_pos_seen = var.end 208 | 209 | if (hom_block_end and hom_block_start): 210 | # and check for block once more after seeing last var 211 | block_size = hom_block_end - hom_block_start + 1 212 | if current_block_hets / block_size * 1000000 > args.max_hets or current_block_hets /current_block_homs > args.max_het_fraction : 213 | if block_size > args.shortest_block and current_block_homs > args.minimum_homs: 214 | end_block(current_chr, hom_block_start, hom_block_end, current_block_hets, block_homs) 215 | 216 | 217 | 218 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rhocall 2 | Call regions of homozygosity and make tentative UPD calls 3 | 4 | ## Usage ## 5 | 6 | ``` 7 | Usage: rhocall [OPTIONS] COMMAND [ARGS]... 8 | 9 | Options: 10 | --help Show this message and exit. 11 | 12 | Commands: 13 | aggregate Aggregate runs of autozygosity from rhofile... 14 | annotate Markup VCF file using rho-calls. 15 | call Call runs of autozygosity. 16 | tally Tally runs of autozygosity from rhofile. 17 | viz Plot binned zygosity and RHO-regions. 18 | ``` 19 | ### rhocall call ### 20 | ``` 21 | Usage: rhocall call [OPTIONS] VCF 22 | 23 | Call runs of autozygosity. 24 | 25 | Options: 26 | -m, --max_hets FLOAT Max heterozygotes per Mb in a homozygous 27 | block 28 | -f, --max_het_fraction FLOAT Max heterozygotes over homozygotes fraction 29 | in a homozygous block 30 | -n, --minimum_homs INTEGER Minimum absolute number of homozygotes to 31 | report a block 32 | -s, --shortest_block INTEGER Shortest block 33 | -u, --flag_upd_at_fraction FLOAT 34 | Flag UPD if homozygous blocks span this 35 | fraction of total chr size 36 | -k, --individual INTEGER Index of individual in vcf/bcf, 0-based. 37 | -s, --block_constant INTEGER Should be adapted to type of analysis(exome 38 | or genome) 39 | -v, --verbose 40 | --help Show this message and exit. 41 | ``` 42 | 43 | ### rhocall aggregate #### 44 | ``` 45 | Usage: rhocall aggregate [OPTIONS] ROH 46 | 47 | Aggregate runs of autozygosity from rhofile into windowed rho BED file. 48 | Accepts a bcftools roh style TSV-file with CHR,POS,AZ,QUAL. 49 | 50 | Options: 51 | -q, --quality_threshold FLOAT Minimum quality trusted to start or end ROH- 52 | windows. 53 | -v, --verbose 54 | -o, --output FILENAME 55 | --help Show this message and exit. 56 | ``` 57 | 58 | ### rhocall tally ### 59 | ``` 60 | Usage: rhocall tally [OPTIONS] ROH 61 | 62 | Tally runs of autozygosity from rhofile. Accepts a bcftools roh style TSV- 63 | file with CHR,POS,AZ,QUAL. 64 | 65 | Options: 66 | -q, --quality_threshold FLOAT Minimum quality that counts towards region 67 | totals. 68 | -u, --flag_upd_at_fraction FLOAT 69 | Flag UPD if this fraction of chr quality 70 | positions called AZ. 71 | -v, --verbose 72 | -o, --output FILENAME 73 | --help Show this message and exit. 74 | ``` 75 | 76 | ### rhocall annotate ### 77 | ``` 78 | Usage: rhocall annotate [OPTIONS] VCF 79 | 80 | Markup VCF file using rho-calls. Use BED file to mark all variants in AZ 81 | windows. Alternatively, use a bcftools v>=1.4 file with RG entries to mark 82 | all vars. With the --no-v14 flag, use an older bcftools v<=1.2 style roh 83 | TSV to mark only selected AZ variants. Roh is broken in bcftools v1.3 - 84 | do not use. 85 | 86 | Options: 87 | -r FILENAME Bcftools roh style TSV file with 88 | CHR,POS,AZ,QUAL. 89 | --v14 / --no-v14 Bcftools v1.4 or newer roh file including RG 90 | calls. 91 | --select-sample TEXT Select sample to use for bcftools v1.4 or 92 | newer roh file including RG calls and 93 | multiple indidviduals. 94 | -b FILENAME BED file with AZ windows. 95 | -q, --quality_threshold FLOAT Minimum quality calls that are imported in 96 | region totals. 97 | -u, --flag_upd_at_fraction FLOAT 98 | Flag UPD if this fraction of chr quality 99 | positions called AZ. 100 | -v, --verbose 101 | -o, --output FILENAME 102 | --help Show this message and exit. 103 | ``` 104 | ### rhocall viz ### 105 | 106 | ```Usage: rhocall viz [OPTIONS] VCF 107 | 108 | Plot binned zygosity and RHO-regions. 109 | 110 | Options: 111 | --out_dir PATH Output directory. The files will be named 112 | out_dir/chr.png. One picture is drawn per 113 | chromosome. [required] 114 | --wig / --no-wig Produce wig file. 115 | -p, --pointsize INTEGER Size of the points (pixels) 116 | -r, --rho FILENAME Input RHO file produced from rhocall [required] 117 | -m, --minsnv INTEGER Minimum number of snvs for each plotted bin 118 | -M, --maxsnv INTEGER Maximum number of snvs for each plotted bin 119 | --minaf FLOAT Minimum allele frequency. This variable must be 120 | set to 0 if the allele frequency is not 121 | annotated. 122 | --maxaf FLOAT Maximum allele frequency 123 | --aftag TEXT The allele frequency tag to use. 124 | -q, --minqual INTEGER Do not add SNVs to a bin if their quality is 125 | less than this value. 126 | --mnv / --no-mnv Include MNV 127 | -w, --window INTEGER Window size(bases) 128 | -s, --rsid / --no-rsid Skip variants not containing an rsid 129 | -n, --filter / --no-filter include variants, even if they are not labeled 130 | PASS 131 | -v, --verbose 132 | --help Show this message and exit. 133 | ``` 134 | 135 | ### rhoviz (standalone version) ### 136 | 137 | ``` 138 | Usage: rhoviz [OPTIONS] -i input.vcf -r rho.tab -d output_dir 139 | 140 | Visualise the rhocall output file. Genomic regions labeled RHO are visualised as red lines. 141 | Additionally, the fraction of homozygous snps are visualised as black dots. 142 | 143 | Options: 144 | -r FILENAME Input RHO file produced from rhocall 145 | 146 | --help Show this message and exit. 147 | 148 | -i Input vcf file 149 | 150 | -d output directory, the files will be named dir/chr.png, 151 | 152 | -w window size(bases) (default = 10 000) 153 | 154 | -m minimum number of snvs for each plotted bin (default =2) 155 | 156 | -M maximum number of snvs for each plotted bin (default = 20) 157 | 158 | --minaf minimum allele frequency (default = 0.1) 159 | (this variable must be set to 0 if the allele frequency is not annotated) 160 | 161 | --maxaf maximum allele frequency (default = 0.9) 162 | 163 | --aftag AFTAG the allele frequency tag (default = 1000GAF) 164 | 165 | -q do not add snvs to a bin if there quality is less than this value (default = 60) 166 | -p Size of the points (pixels) 167 | 168 | -n include variants, even if they are not labeled PASS 169 | 170 | 171 | ``` 172 | 173 | ## Examples ## 174 | 175 | ### Suggested workflow ### 176 | 177 | #### Preparation #### 178 | ``` 179 | bcftools query -f'%CHROM\t%POS\t%REF,%ALT\t%INFO/AF\n' popfreq.vcf.gz | bgzip -c > popfreq.tab.gz 180 | ``` 181 | 182 | #### Call ROH with bcftools #### 183 | Please see the [samtools project](https://samtools.github.io/bcftools/) for installation instructions, and 184 | please refer to [Narasimhan et al, 2016](http://bioinformatics.oxfordjournals.org/content/early/2016/01/30/bioinformatics.btw044) regarding method details. 185 | 186 | ``` 187 | bcftools roh --AF-file popfreq.tab.gz -I sample.bcf > sample.roh 188 | ``` 189 | 190 | #### Annotate variant file (VCF/BCF) with ROH calls #### 191 | ``` 192 | rhocall annotate --v14 -r sample.roh -o sample.14.rho.vcf sample.bcf 193 | ``` 194 | 195 | #### Legacy mode for bcftools<1.4: Aggregate ROH calls into windows and annotate 196 | ``` 197 | rhocall aggregate sample.roh -o sample.roh.bed 198 | rhocall annotate -b sample.roh.bed -o sample.rho.vcf sample.bcf 199 | ``` 200 | 201 | #### Obtain per chromosome overview #### 202 | ``` 203 | rhocall tally sample.roh -o sample.roh.tally.tsv 204 | ``` 205 | 206 | #### Export calls and zygosity data to wig and bed files #### 207 | ``` 208 | rhocall viz --rho sample.roh --wig --out_dir rhocall sample.vcf 209 | ``` 210 | 211 | ### Additional usage examples ### 212 | 213 | ``` 214 | bcftools query -f'%CHROM\t%POS\t%REF,%ALT\t%INFO/AF\n' anon-SweGen_STR_NSPHS_1000samples_snp_freq_hg19.vcf.gz | bgzip -c > anon_SweGen_161019_snp_freq_hg19.tab.gz 215 | bcftools roh --AF-file anon_SweGen_161019_snp_freq_hg19.tab.gz -I 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.bcf > 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh 216 | 217 | # bcftools <=1.2 218 | rhocall tally 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh -o 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh.tally.tsv 219 | rhocall annotate --no-v14 -r 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.bcf -o 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh.vcf 220 | rhocall aggregate 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh -o 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh.bed 221 | rhocall annotate -b 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.roh.bed -o 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.rho.vcf 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.bcf 222 | 223 | # bcftools >=1.4 224 | rhocall annotate --v14 -r 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.14.roh -o 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.14.rho.vcf 2016-14676_sorted_md_rreal_brecal_gvcf_vrecal_comb_BOTH.bcf 225 | 226 | # visualize: (using bcftools v1.9) 227 | bcftools roh --AF-file /home/proj/development/rare-disease/references/grch37_anon_swegen_snp_-2016-10-19-.tab.gz -I F0010931_sorted_md_brecal_haptc_vrecal_comb_BOTH.bcf > F0010931_sorted_md_brecal_haptc_vrecal_comb_BOTH.roh 228 | rhocall viz --wig --out_dir rhocall --aftag GNOMADAF --rho F0010931_sorted_md_brecal_haptc_vrecal_comb_BOTH.roh F0010931_sorted_md_brecal_haptc_vrecal_comb_rhocall_vt_frqf_vep_parsed_snpeff_ranked_BOTH.vcf 229 | ``` 230 | 231 | ## Test files ## 232 | The test directory contains test files from the [BCFtools/RoH project](https://samtools.github.io/bcftools/howtos/roh-calling.html). 233 | 234 | ## Installation ## 235 | The cyvcf2 install process appears to be jinxed on certain systems/setups. 236 | In practice this means that a chained pip install on a naive system may fail. Installation of each requirement for cyvcf2 prior to installing it appears to work unconditionally. 237 | ``` 238 | pip install numpy; pip install Cython 239 | pip install -r requirements.txt 240 | pip install -e . 241 | ``` 242 | -------------------------------------------------------------------------------- /rhocall/cli.py: -------------------------------------------------------------------------------- 1 | import click 2 | import logging 3 | import inspect 4 | import os 5 | 6 | from cyvcf2 import VCF 7 | 8 | from rhocall.log import configure_stream, LEVELS 9 | from .run_rho import run_rhocall 10 | from .run_annotate import run_annotate 11 | from .run_annotate_bcfroh import run_annotate_rg 12 | from .run_annotate_var import run_annotate_var 13 | from .run_tally import run_tally 14 | from .run_aggregate import run_aggregate 15 | from .run_viz import generate_bins, generate_plots, generate_wig, extract_roh 16 | 17 | from .prints import output_bed_header 18 | 19 | from rhocall import __version__ 20 | 21 | logger = logging.getLogger(__name__) 22 | handler = logging.StreamHandler() 23 | formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") 24 | handler.setFormatter(formatter) 25 | logger.addHandler(handler) 26 | logger.setLevel(logging.INFO) 27 | 28 | 29 | @click.group() 30 | @click.version_option(__version__) 31 | def cli(): 32 | pass 33 | 34 | 35 | @click.command() 36 | @click.argument("vcf", type=click.Path(exists=True)) 37 | @click.option( 38 | "--max_hets", "-m", default=2.0, help="Max heterozygotes per Mb in a homozygous block" 39 | ) 40 | @click.option( 41 | "--max_het_fraction", 42 | "-f", 43 | type=float, 44 | default=2, 45 | help="Max heterozygotes over homozygotes fraction in a homozygous block", 46 | ) 47 | @click.option( 48 | "--minimum_homs", 49 | "-n", 50 | default=5, 51 | help="Minimum absolute number of homozygotes to report a block", 52 | ) 53 | @click.option("--shortest_block", "-s", default=100000, help="Shortest block") 54 | @click.option( 55 | "--flag_upd_at_fraction", 56 | "-u", 57 | default=0.3, 58 | help="Flag UPD if homozygous blocks span this fraction of total chr size", 59 | ) 60 | @click.option("--individual", "-k", type=int, help="Index of individual in vcf/bcf, 0-based.") 61 | @click.option( 62 | "--block_constant", 63 | "-s", 64 | default=100000, 65 | help="Should be adapted to type of analysis(exome or genome)", 66 | ) 67 | @click.option("-v", "--verbose", count=True, default=2) 68 | def call( 69 | ctx, 70 | vcf, 71 | max_hets, 72 | max_het_fraction, 73 | minimum_homs, 74 | shortest_block, 75 | flag_upd_at_fraction, 76 | individual, 77 | block_constant, 78 | verbose, 79 | ): 80 | """Call runs of autozygosity. (deprecated: use bcftools roh instead.""" 81 | loglevel = LEVELS.get(min(verbose, 3)) 82 | configure_stream(level=loglevel) 83 | 84 | proband_vcf = VCF(vcf) 85 | 86 | if len(proband_vcf.samples) > 1: 87 | try: 88 | individual = int(individual) 89 | except TypeError: 90 | logger.warning("Please specify which individual to check.") 91 | ctx.abort() 92 | else: 93 | individual = 0 94 | 95 | output_bed_header() 96 | 97 | run_rhocall( 98 | proband_vcf=proband_vcf, 99 | block_constant=block_constant, 100 | max_hets=max_hets, 101 | max_het_fraction=max_het_fraction, 102 | minimum_homs=minimum_homs, 103 | shortest_block=shortest_block, 104 | flag_UPD_at_fraction=flag_upd_at_fraction, 105 | individual=individual, 106 | ) 107 | 108 | 109 | @click.command() 110 | @click.argument("roh", type=click.File("r")) 111 | @click.option( 112 | "--quality_threshold", 113 | "-q", 114 | default=10.0, 115 | help="Minimum quality that counts towards region totals.", 116 | ) 117 | @click.option( 118 | "--flag_upd_at_fraction", 119 | "-u", 120 | default=0.4, 121 | help="Flag UPD if this fraction of chr quality positions called AZ.", 122 | ) 123 | @click.option("-v", "--verbose", count=True, default=2) 124 | @click.option("--output", "-o", type=click.File("w"), default="-") 125 | def tally(roh, quality_threshold, flag_upd_at_fraction, output, verbose): 126 | """Tally runs of autozygosity from rhofile. 127 | Accepts a bcftools roh style TSV-file with CHR,POS,AZ,QUAL.""" 128 | loglevel = LEVELS.get(min(verbose, 3)) 129 | configure_stream(level=loglevel) 130 | 131 | logger.info("Running rhocall tally {0}".format(__version__)) 132 | 133 | run_tally( 134 | roh=roh, 135 | quality_threshold=quality_threshold, 136 | flag_upd_at_fraction=flag_upd_at_fraction, 137 | output=output, 138 | ) 139 | 140 | 141 | @click.command() 142 | @click.argument("roh", type=click.File("r")) 143 | @click.option( 144 | "--quality_threshold", 145 | "-q", 146 | default=10.0, 147 | help="Minimum quality trusted to start or end ROH-windows.", 148 | ) 149 | @click.option("-v", "--verbose", count=True, default=2) 150 | @click.option("--output", "-o", type=click.File("w"), default="-") 151 | def aggregate(roh, quality_threshold, output, verbose): 152 | """Aggregate runs of autozygosity from rhofile into windowed rho BED file. 153 | Accepts a bcftools roh style TSV-file with CHR,POS,AZ,QUAL.""" 154 | loglevel = LEVELS.get(min(verbose, 3)) 155 | configure_stream(level=loglevel) 156 | 157 | logger.info("Running rhocall aggregate {0}".format(__version__)) 158 | 159 | run_aggregate(roh=roh, quality_threshold=quality_threshold, output=output) 160 | 161 | 162 | @click.command() 163 | @click.argument("vcf", type=click.Path(exists=True)) 164 | @click.option( 165 | "roh", "-r", type=click.File("r"), help="Bcftools roh style TSV file with CHR,POS,AZ,QUAL." 166 | ) 167 | @click.option( 168 | "--v14/--no-v14", default=True, help="Bcftools v1.4 or newer roh file including RG calls." 169 | ) 170 | @click.option( 171 | "--select-sample", default=None, help="Select sample to use for bcftools v1.4 or newer roh file including RG calls and multiple indidviduals." 172 | ) 173 | @click.option("bed", "-b", type=click.File("r"), help="BED file with AZ windows.") 174 | @click.option( 175 | "--quality_threshold", 176 | "-q", 177 | default=10.0, 178 | help="Minimum quality calls that are imported in region totals.", 179 | ) 180 | @click.option( 181 | "--flag_upd_at_fraction", 182 | "-u", 183 | default=0.4, 184 | help="Flag UPD if this fraction of chr quality positions called AZ.", 185 | ) 186 | @click.option("-v", "--verbose", count=True, default=2) 187 | @click.option("--output", "-o", type=click.File("w"), default="-") 188 | def annotate(vcf, roh, bed, v14, quality_threshold, flag_upd_at_fraction, output, verbose, select_sample): 189 | """Markup VCF file using rho-calls. Use BED file to mark all variants in AZ 190 | windows. Alternatively, use a bcftools v>=1.4 file with RG entries to mark 191 | all vars. With the --no-v14 flag, use an older bcftools v<=1.2 style roh TSV 192 | to mark only selected AZ variants. Roh is broken in bcftools v1.3 193 | - do not use.""" 194 | loglevel = LEVELS.get(min(verbose, 3)) 195 | configure_stream(level=loglevel) 196 | 197 | proband_vcf = VCF(vcf) 198 | 199 | # add this command to VCF header 200 | 201 | ## This is for logging the command line string ## 202 | frame = inspect.currentframe() 203 | args, _, _, values = inspect.getargvalues(frame) 204 | argument_list = [i + "=" + str(values[i]) for i in values if values[i] and i not in ["frame"]] 205 | 206 | logger.info("Running rhocall annotate {0}".format(__version__)) 207 | logger.debug("Arguments: {0}".format(", ".join(argument_list))) 208 | 209 | ## add additional tags to VCF header 210 | proband_vcf.add_to_header("##rhocall_version={0}".format(__version__)) 211 | proband_vcf.add_to_header("##rhocall_arguments={0}".format(", ".join(argument_list))) 212 | 213 | if roh and not bed and not v14: 214 | run_annotate_var( 215 | proband_vcf=proband_vcf, 216 | roh=roh, 217 | quality_threshold=quality_threshold, 218 | flag_upd_at_fraction=flag_upd_at_fraction, 219 | output=output, 220 | ) 221 | elif roh and v14 and not bed: 222 | run_annotate_rg( 223 | proband_vcf=proband_vcf, 224 | bcfroh=roh, 225 | quality_threshold=quality_threshold, 226 | flag_upd_at_fraction=flag_upd_at_fraction, 227 | output=output, 228 | select_sample=select_sample, 229 | ) 230 | elif bed and not roh: 231 | run_annotate( 232 | proband_vcf=proband_vcf, 233 | bed=bed, 234 | quality_threshold=quality_threshold, 235 | flag_upd_at_fraction=flag_upd_at_fraction, 236 | output=output, 237 | ) 238 | else: 239 | click.echo( 240 | """Cannot use both BED and ROH at once. Please apply 241 | them sequentially instead.""" 242 | ) 243 | 244 | 245 | @click.command() 246 | @click.argument("vcf", type=click.File("r"), required=True) # help='Input (sorted) vcf file' 247 | @click.option( 248 | "--out_dir", 249 | type=click.Path(exists=False), 250 | required=True, 251 | help="Output directory. The files will be named out_dir/chr.png. One picture is drawn per chromosome.", 252 | ) 253 | @click.option("--wig/--no-wig", default=True, help="Produce wig file.") 254 | @click.option("--pointsize", "-p", type=int, default=8, help="Size of the points (pixels)") 255 | @click.option( 256 | "--rho", "-r", type=click.File("r"), required=True, help="Input RHO file produced from rhocall" 257 | ) 258 | @click.option( 259 | "--minsnv", "-m", type=int, default=2, help="Minimum number of snvs for each plotted bin" 260 | ) 261 | @click.option( 262 | "--maxsnv", "-M", type=int, default=20, help="Maximum number of snvs for each plotted bin" 263 | ) 264 | @click.option( 265 | "--minaf", 266 | type=float, 267 | default=0.1, 268 | help="Minimum allele frequency. This variable must be set to 0 if the allele frequency is not annotated.", 269 | ) 270 | @click.option("--maxaf", type=float, default=0.9, help="Maximum allele frequency") 271 | @click.option("--aftag", type=str, default="1000GAF", help="The allele frequency tag to use.") 272 | @click.option( 273 | "--minqual", 274 | "-q", 275 | type=int, 276 | default=98, 277 | help="Do not add SNVs to a bin if their quality is less than this value.", 278 | ) 279 | @click.option("--mnv/--no-mnv", default=False, help="Include MNV") 280 | @click.option("--window", "-w", type=int, default=10000, help="Window size(bases)") 281 | @click.option("--rsid/--no-rsid", "-s", default=False, help="Skip variants not containing an rsid") 282 | @click.option( 283 | "--filter/--no-filter", 284 | "-n", 285 | default=True, 286 | help="include variants, even if they are not labeled PASS", 287 | ) 288 | @click.option("-v", "--verbose", count=True, default=2) 289 | def viz( 290 | vcf, 291 | out_dir, 292 | wig, 293 | pointsize, 294 | rho, 295 | minsnv, 296 | maxsnv, 297 | minaf, 298 | maxaf, 299 | aftag, 300 | minqual, 301 | mnv, 302 | window, 303 | rsid, 304 | filter, 305 | verbose, 306 | ): 307 | """Plot binned zygosity and RHO-regions.""" 308 | 309 | loglevel = LEVELS.get(min(verbose, 3)) 310 | configure_stream(level=loglevel) 311 | 312 | if not os.access(out_dir, os.F_OK): 313 | os.mkdir(out_dir) 314 | 315 | binned_zygosity = generate_bins( 316 | vcf, window, filter, mnv, minqual, rsid, minaf, aftag, maxaf, minsnv 317 | ) 318 | roh = extract_roh(rho) 319 | if wig: 320 | out_file_basename = out_dir + "/output" 321 | generate_wig(binned_zygosity, roh, window, out_file_basename) 322 | else: 323 | generate_plots(binned_zygosity, roh, window, pointsize, out_dir) 324 | 325 | 326 | cli.add_command(call) 327 | cli.add_command(tally) 328 | cli.add_command(aggregate) 329 | cli.add_command(annotate) 330 | cli.add_command(viz) 331 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------