├── DESCRIPTION.rst ├── .gitignore ├── requirements.txt ├── scripts ├── DCC └── getcircfasta ├── DCC ├── data │ ├── DCC.Repeats │ ├── samplesheet │ ├── mate1 │ └── mate2 ├── __init__.py ├── IntervalTree.py ├── fix2chimera.py ├── circFilter.py ├── CombineCounts.py ├── circAnnotate.py ├── findcircRNA.py ├── genecount.py ├── Circ_nonCirc_Exon_Match.py └── main.py ├── MANIFEST.in ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── setup.py ├── README.rst └── LICENSE /DESCRIPTION.rst: -------------------------------------------------------------------------------- 1 | # Detect circRNAs from chimera 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .idea* 3 | build/* 4 | DCC.egg* 5 | dist/* -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pysam>=0.16.0.1 2 | numpy 3 | pandas 4 | Cython 5 | -------------------------------------------------------------------------------- /scripts/DCC: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | import DCC.main 4 | 5 | DCC.main.main() 6 | -------------------------------------------------------------------------------- /DCC/data/DCC.Repeats: -------------------------------------------------------------------------------- 1 | None rn6_rmsk exon 1 1 32.000000 + . gene_id "(ATAC)n"; transcript_id "(ATAC)n"; 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include DESCRIPTION.rst 2 | include README.rst 3 | include LICENSE 4 | recursive-include data/Repeats 5 | include LICENSE data/chimeric_junctions 6 | include LICENSE data/mate1 7 | include LICENSE data/mate2 8 | -------------------------------------------------------------------------------- /DCC/__init__.py: -------------------------------------------------------------------------------- 1 | # Import modules 2 | from .findcircRNA import Findcirc 3 | from .circFilter import Circfilter 4 | from .circAnnotate import CircAnnotate 5 | from .genecount import Genecount 6 | from .CombineCounts import Combine 7 | from .Circ_nonCirc_Exon_Match import CircNonCircExon 8 | from .IntervalTree import IntervalTree 9 | from .main import main 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Command line used for the command 13 | 2. Complete error message 14 | 15 | **Screenshots** 16 | If applicable, add screenshots to help explain your problem. 17 | 18 | **Desktop (please complete the following information):** 19 | - OS: [e.g. Debian 8.6, Ubuntu 18.04] 20 | - Python version [e.g. 3.6, 3.4] 21 | - Version [e.g. 1.1.0.1] 22 | 23 | **Additional context** 24 | Add any other context about the problem here. 25 | -------------------------------------------------------------------------------- /DCC/data/samplesheet: -------------------------------------------------------------------------------- 1 | /data/projects/Westholm_Drosophila/SRR1197279/SRR1197279Chimeric.out.junction 2 | /data/projects/Westholm_Drosophila/SRR1197275/SRR1197275Chimeric.out.junction 3 | /data/projects/Westholm_Drosophila/SRR1197273/SRR1197273Chimeric.out.junction 4 | /data/projects/Westholm_Drosophila/SRR1197274/SRR1197274Chimeric.out.junction 5 | /data/projects/Westholm_Drosophila/SRR1197276/SRR1197276Chimeric.out.junction 6 | /data/projects/Westholm_Drosophila/SRR1197272/SRR1197272Chimeric.out.junction 7 | /data/projects/Westholm_Drosophila/SRR1197294/SRR1197294Chimeric.out.junction 8 | /data/projects/Westholm_Drosophila/SRR1197486/SRR1197486Chimeric.out.junction 9 | /data/projects/Westholm_Drosophila/SRR1197485/SRR1197485Chimeric.out.junction 10 | /data/projects/Westholm_Drosophila/SRR1197484/SRR1197484Chimeric.out.junction 11 | /data/projects/Westholm_Drosophila/SRR1197481/SRR1197481Chimeric.out.junction 12 | /data/projects/Westholm_Drosophila/SRR1197293/SRR1197293Chimeric.out.junction 13 | /data/projects/Westholm_Drosophila/SRR1197472/SRR1197472Chimeric.out.junction 14 | /data/projects/Westholm_Drosophila/SRR1197473/SRR1197473Chimeric.out.junction 15 | /data/projects/Westholm_Drosophila/SRR1197474/SRR1197474Chimeric.out.junction 16 | /data/projects/Westholm_Drosophila/SRR1197362/SRR1197362Chimeric.out.junction 17 | /data/projects/Westholm_Drosophila/SRR1197361/SRR1197361Chimeric.out.junction 18 | /data/projects/Westholm_Drosophila/SRR1197359/SRR1197359Chimeric.out.junction -------------------------------------------------------------------------------- /DCC/data/mate1: -------------------------------------------------------------------------------- 1 | /data/projects/Westholm_Drosophila/SRR1197279/mate1/SRR1197279_1Chimeric.out.junction 2 | /data/projects/Westholm_Drosophila/SRR1197275/mate1/SRR1197275_1Chimeric.out.junction 3 | /data/projects/Westholm_Drosophila/SRR1197273/mate1/SRR1197273_1Chimeric.out.junction 4 | /data/projects/Westholm_Drosophila/SRR1197274/mate1/SRR1197274_1Chimeric.out.junction 5 | /data/projects/Westholm_Drosophila/SRR1197276/mate1/SRR1197276_1Chimeric.out.junction 6 | /data/projects/Westholm_Drosophila/SRR1197272/mate1/SRR1197272_1Chimeric.out.junction 7 | /data/projects/Westholm_Drosophila/SRR1197294/mate1/SRR1197294_1Chimeric.out.junction 8 | /data/projects/Westholm_Drosophila/SRR1197486/mate1/SRR1197486_1Chimeric.out.junction 9 | /data/projects/Westholm_Drosophila/SRR1197485/mate1/SRR1197485_1Chimeric.out.junction 10 | /data/projects/Westholm_Drosophila/SRR1197484/mate1/SRR1197484_1Chimeric.out.junction 11 | /data/projects/Westholm_Drosophila/SRR1197481/mate1/SRR1197481_1Chimeric.out.junction 12 | /data/projects/Westholm_Drosophila/SRR1197293/mate1/SRR1197293_1Chimeric.out.junction 13 | /data/projects/Westholm_Drosophila/SRR1197472/mate1/SRR1197472_1Chimeric.out.junction 14 | /data/projects/Westholm_Drosophila/SRR1197473/mate1/SRR1197473_1Chimeric.out.junction 15 | /data/projects/Westholm_Drosophila/SRR1197474/mate1/SRR1197474_1Chimeric.out.junction 16 | /data/projects/Westholm_Drosophila/SRR1197362/mate1/SRR1197362_1Chimeric.out.junction 17 | /data/projects/Westholm_Drosophila/SRR1197361/mate1/SRR1197361_1Chimeric.out.junction 18 | /data/projects/Westholm_Drosophila/SRR1197359/mate1/SRR1197359_1Chimeric.out.junction -------------------------------------------------------------------------------- /DCC/data/mate2: -------------------------------------------------------------------------------- 1 | /data/projects/Westholm_Drosophila/SRR1197279/mate2/SRR1197279_2Chimeric.out.junction 2 | /data/projects/Westholm_Drosophila/SRR1197275/mate2/SRR1197275_2Chimeric.out.junction 3 | /data/projects/Westholm_Drosophila/SRR1197273/mate2/SRR1197273_2Chimeric.out.junction 4 | /data/projects/Westholm_Drosophila/SRR1197274/mate2/SRR1197274_2Chimeric.out.junction 5 | /data/projects/Westholm_Drosophila/SRR1197276/mate2/SRR1197276_2Chimeric.out.junction 6 | /data/projects/Westholm_Drosophila/SRR1197272/mate2/SRR1197272_2Chimeric.out.junction 7 | /data/projects/Westholm_Drosophila/SRR1197294/mate2/SRR1197294_2Chimeric.out.junction 8 | /data/projects/Westholm_Drosophila/SRR1197486/mate2/SRR1197486_2Chimeric.out.junction 9 | /data/projects/Westholm_Drosophila/SRR1197485/mate2/SRR1197485_2Chimeric.out.junction 10 | /data/projects/Westholm_Drosophila/SRR1197484/mate2/SRR1197484_2Chimeric.out.junction 11 | /data/projects/Westholm_Drosophila/SRR1197481/mate2/SRR1197481_2Chimeric.out.junction 12 | /data/projects/Westholm_Drosophila/SRR1197293/mate2/SRR1197293_2Chimeric.out.junction 13 | /data/projects/Westholm_Drosophila/SRR1197472/mate2/SRR1197472_2Chimeric.out.junction 14 | /data/projects/Westholm_Drosophila/SRR1197473/mate2/SRR1197473_2Chimeric.out.junction 15 | /data/projects/Westholm_Drosophila/SRR1197474/mate2/SRR1197474_2Chimeric.out.junction 16 | /data/projects/Westholm_Drosophila/SRR1197362/mate2/SRR1197362_2Chimeric.out.junction 17 | /data/projects/Westholm_Drosophila/SRR1197361/mate2/SRR1197361_2Chimeric.out.junction 18 | /data/projects/Westholm_Drosophila/SRR1197359/mate2/SRR1197359_2Chimeric.out.junction -------------------------------------------------------------------------------- /scripts/getcircfasta: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # This script is aimed to get circRNA exon sequences 3 | #### Iput: 4 | #--- circRNA coordinates 5 | #--- reference genome fasta file 6 | #--- exon annotation bedfile 7 | 8 | ## NOTICE 9 | # The circRNA coordinates, reference genome and exon annotation should be the same release version, 10 | # the circRNA coordinates should match with exon annotation coordinates, i.e. for chromosome1: chr1 or 1 11 | 12 | #### Output: a fasta file with sequence and circRNA coordinates 13 | 14 | # import 15 | from pybedtools import BedTool 16 | from optparse import OptionParser 17 | 18 | usage = "usage: %prog -f genomefastafile -c circcoordinates -e exonbedfile -o outputfile" 19 | parser = OptionParser(usage=usage) 20 | parser.add_option("-f", "--fasta", dest="fasta", 21 | help="The reference genome fasta file") 22 | parser.add_option("-c", "--circ", dest="circ", 23 | help="tab delimited circRNA coordinates") 24 | parser.add_option("-e", "--exon", dest="exon", 25 | help="tab delimited exon annotation file, bedfile format") 26 | parser.add_option("-m", "--maxL", dest="maxL", type='int', default=int(5000), 27 | help="Maximum length of the circRNA exon sequence.") 28 | parser.add_option("-o", "--output", dest="output", 29 | help="output circRNA sequence in a fasta format") 30 | (options, args) = parser.parse_args() 31 | 32 | 33 | def getfa(fasta): 34 | # a string to store fasta sequence 35 | #print 'NOTE: Remove the duplicated exons in the exon file!' 36 | regionSet = set() # A set to store the exon regions to avoid duplicates 37 | seq = '' 38 | 39 | for index, itm in enumerate(fasta): 40 | if itm.startswith('>'): 41 | if itm not in regionSet: 42 | seq=seq+fasta[index+1].strip('\n') 43 | regionSet.add(itm) 44 | 45 | return seq 46 | 47 | # read the circRNA one by one 48 | circfile = open(options.circ).read().splitlines() 49 | annotation = BedTool(options.exon) 50 | fasta = BedTool(options.fasta) 51 | 52 | def intersectCirc(circfile,annotation,fasta): 53 | output = open(options.output,'w') 54 | 55 | for itm in circfile: 56 | circ = BedTool([itm]) 57 | a = annotation.intersect(circ) 58 | a = a.sequence(fi=fasta) 59 | fa = open(a.seqfn).readlines() 60 | seq = getfa(fa) 61 | 62 | if len(seq) < options.maxL: 63 | # write in a fasta format 64 | output.write('>' +itm + '\n') 65 | output.write(seq+'\n') 66 | 67 | output.close() 68 | 69 | intersectCirc(circfile=circfile,annotation=annotation,fasta=fasta) 70 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """A setuptools based setup module. 2 | 3 | See: 4 | https://packaging.python.org/en/latest/distributing.html 5 | https://github.com/pypa/sampleproject 6 | """ 7 | 8 | # Always prefer setuptools over distutils 9 | from codecs import open 10 | from os import path 11 | from setuptools import setup 12 | 13 | here = path.abspath(path.dirname(__file__)) 14 | 15 | # Get the long description from the relevant file 16 | with open(path.join(here, 'README.rst')) as f: 17 | long_description = f.read() 18 | 19 | setup( 20 | name='DCC', 21 | 22 | # Versions should comply with PEP440. For a discussion on single-sourcing 23 | # the version across setup.py and the project code, see 24 | # https://packaging.python.org/en/latest/single_source_version.html 25 | version='0.5.0', 26 | 27 | description='Detect circRNAs from chimeras', 28 | long_description=long_description, 29 | 30 | # The project's main homepage. 31 | url='https://github.com/dieterich-lab/DCC', 32 | 33 | # Author details 34 | 35 | maintainer='Tobias Jakobi', 36 | maintainer_email='Tobias.Jakobi@med.Uni-Heidelberg.DE', 37 | 38 | author='Jun Cheng', 39 | author_email='s6juncheng@gmail.com', 40 | 41 | 42 | # Choose your license 43 | license='License :: OSI Approved :: GNU General Public License (GPL)', 44 | 45 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 46 | classifiers=[ 47 | # How mature is this project? Common values are 48 | # 3 - Alpha 49 | # 4 - Beta 50 | # 5 - Production/Stable 51 | 'Development Status :: 5 - Production/Stable', 52 | 53 | # Indicate who your project is intended for 54 | 'Intended Audience :: Science/Research', 55 | 'Topic :: Scientific/Engineering :: Bio-Informatics', 56 | 57 | # Pick your license as you wish (should match "license" above) 58 | 'License :: OSI Approved :: GNU General Public License (GPL)', 59 | 60 | # Specify the Python versions you support here. In particular, ensure 61 | # that you indicate whether you support Python 2, Python 3 or both. 62 | # 'Programming Language :: Python :: 2', 63 | # 'Programming Language :: Python :: 2.6', 64 | # 'Programming Language :: Python :: 2.7', 65 | # 'Programming Language :: Python :: 3', 66 | # 'Programming Language :: Python :: 3.2', 67 | # 'Programming Language :: Python :: 3.3', 68 | # 'Programming Language :: Python :: 3.4', 69 | 'Programming Language :: Python :: 3.5', 70 | 'Programming Language :: Python :: 3.6', 71 | 'Programming Language :: Python :: 3.7', 72 | 'Programming Language :: Python :: 3.8', 73 | 74 | ], 75 | 76 | # What does your project relate to? 77 | keywords='circRNA detection and quantification', 78 | 79 | # You can just specify the packages manually here if your project is 80 | # simple. Or you can use find_packages(). 81 | packages=['DCC'], 82 | 83 | # setup_requires=['Cython','pysam','matplotlib'], 84 | 85 | # List run-time dependencies here. These will be installed by pip when 86 | # your project is installed. For an analysis of "install_requires" vs pip's 87 | # requirements files see: 88 | # https://packaging.python.org/en/latest/requirements.html 89 | install_requires=[ 90 | 'HTSeq', 91 | 'pysam >= 0.16.0.1', 92 | # 'numpy', 93 | # 'pandas', 94 | # 'Cython' 95 | ], 96 | 97 | #install_requires=read('requirements.txt').splitlines(), 98 | 99 | # python_requires='<3', 100 | 101 | # List additional groups of dependencies here (e.g. development 102 | # dependencies). You can install these using the following syntax, 103 | # for example: 104 | # $ pip install -e .[dev,test] 105 | # extras_require={ 106 | # 'dev': ['check-manifest'], 107 | # 'test': ['coverage'], 108 | # }, 109 | 110 | # If there are data files included in your packages that need to be 111 | # installed, specify them here. If using Python 2.6 or less, then these 112 | # have to be included in MANIFEST.in as well. 113 | package_data={ 114 | 'DCC': ['data/DCC.Repeats'], 115 | }, 116 | 117 | # Although 'package_data' is the preferred approach, in some case you may 118 | # need to place data files outside of your packages. See: 119 | # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa 120 | # In this case, 'data_file' will be installed into '/my_data' 121 | # data_files=[('my_data', ['data/data_file'])], 122 | 123 | # To provide executable scripts, use entry points in preference to the 124 | # "scripts" keyword. Entry points provide cross-platform support and allow 125 | # pip to create the appropriate form of executable for the target platform. 126 | entry_points={ 127 | 'console_scripts': [ 128 | 'DCC=DCC:main' 129 | ], 130 | }, 131 | scripts=[ 132 | 'scripts/DCC', 133 | ], 134 | 135 | project_urls={ # Optional 136 | 'Bug Reports': 'https://github.com/dieterich-lab/DCC/issues', 137 | 'Dieterich Lab': 'https://dieterichlab.org', 138 | 'Source': 'https://github.com/dieterich-lab/DCC', 139 | 'Documentation': 'http://docs.circ.tools' 140 | }, 141 | ) 142 | -------------------------------------------------------------------------------- /DCC/IntervalTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Intersects ... faster. Suports GenomicInterval datatype and multiple chromosomes. 3 | Accept GenomicInterval object, with attributes chrom, start, end, strand (optional). 4 | In case of unstranded data, interval.strand == '.' 5 | """ 6 | 7 | import math 8 | import random 9 | 10 | 11 | class IntervalTree(object): 12 | def __init__(self): 13 | self.chroms = {} 14 | 15 | def insert(self, interval, annotation=None): 16 | # This interval is the interval to construct the tree, e.g. gtf annotations 17 | chrom = interval.chrom 18 | start = interval.start 19 | end = interval.end 20 | strand = interval.strand 21 | if interval.chrom in self.chroms: 22 | self.chroms[chrom] = self.chroms[chrom].insert(start, end, strand, 23 | annotation) # self.chroms[chrom] is a IntervalNode object 24 | else: 25 | self.chroms[chrom] = IntervalNode(start, end, strand, annotation) 26 | 27 | def intersect(self, interval, report_func): 28 | # This interval from the query 29 | chrom = interval.chrom 30 | start = interval.start 31 | end = interval.end 32 | strand = interval.strand # query interval strand can be '.' 33 | if chrom in self.chroms: 34 | self.chroms[chrom].intersect(start, end, strand, 35 | report_func) 36 | # use the intersect method of IntervalNode class, need make this function aware of strand 37 | 38 | def traverse(self, func): 39 | for item in self.chroms.values(): 40 | item.traverse(func) 41 | 42 | 43 | class IntervalNode(object): 44 | def __init__(self, start, end, strand=None, annotation=None): 45 | self.priority = math.ceil((-1.0 / math.log(.5)) * math.log(-1.0 / (random.uniform(0, 1) - 1))) 46 | self.start = start 47 | self.end = end 48 | self.maxend = self.end 49 | self.minend = self.end 50 | self.left = None 51 | self.right = None 52 | self.strand = strand 53 | self.annotation = annotation 54 | 55 | def insert(self, start, end, strand=None, annotation=None): 56 | root = self 57 | if start > self.start: 58 | # insert to right tree 59 | if self.right: 60 | self.right = self.right.insert(start, end, strand, annotation) 61 | else: 62 | self.right = IntervalNode(start, end, strand, annotation) 63 | # rebalance tree 64 | if self.priority < self.right.priority: 65 | root = self.rotateleft() 66 | else: 67 | # insert to left tree 68 | if self.left: 69 | self.left = self.left.insert(start, end, strand, annotation) 70 | else: 71 | self.left = IntervalNode(start, end, strand, annotation) 72 | # rebalance tree 73 | if self.priority < self.left.priority: 74 | root = self.rotateright() 75 | if root.right and root.left: 76 | root.maxend = max(root.end, root.right.maxend, root.left.maxend) 77 | root.minend = min(root.end, root.right.minend, root.left.minend) 78 | elif root.right: 79 | root.maxend = max(root.end, root.right.maxend) 80 | root.minend = min(root.end, root.right.minend) 81 | elif root.left: 82 | root.maxend = max(root.end, root.left.maxend) 83 | root.minend = min(root.end, root.left.minend) 84 | return root 85 | 86 | def rotateright(self): 87 | root = self.left 88 | self.left = self.left.right 89 | root.right = self 90 | if self.right and self.left: 91 | self.maxend = max(self.end, self.right.maxend, self.left.maxend) 92 | self.minend = min(self.end, self.right.minend, self.left.minend) 93 | elif self.right: 94 | self.maxend = max(self.end, self.right.maxend) 95 | self.minend = min(self.end, self.right.minend) 96 | elif self.left: 97 | self.maxend = max(self.end, self.left.maxend) 98 | self.minend = min(self.end, self.left.minend) 99 | return root 100 | 101 | def rotateleft(self): 102 | root = self.right 103 | self.right = self.right.left 104 | root.left = self 105 | if self.right and self.left: 106 | self.maxend = max(self.end, self.right.maxend, self.left.maxend) 107 | self.minend = min(self.end, self.right.minend, self.left.minend) 108 | elif self.right: 109 | self.maxend = max(self.end, self.right.maxend) 110 | self.minend = min(self.end, self.right.minend) 111 | elif self.left: 112 | self.maxend = max(self.end, self.left.maxend) 113 | self.minend = min(self.end, self.left.minend) 114 | return root 115 | 116 | ### TODO 117 | def intersect(self, start, end, strand, report_func): 118 | if strand == '.': # unstranded data, not going to compare strand 119 | if start < self.end and end > self.start: 120 | report_func(self) 121 | else: 122 | if start < self.end and end > self.start and strand == self.strand: 123 | report_func(self) 124 | if self.left and start < self.left.maxend: 125 | self.left.intersect(start, end, strand, report_func) 126 | if self.right and end > self.start: 127 | self.right.intersect(start, end, strand, report_func) 128 | 129 | def traverse(self, func): 130 | if self.left: self.left.traverse(func) 131 | func(self) 132 | if self.right: self.right.traverse(func) 133 | -------------------------------------------------------------------------------- /DCC/fix2chimera.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python2 2 | 3 | # If paire end data are used, this module fix the rolling circRNA could not detect by single run problem. 4 | 5 | import os 6 | import sys 7 | 8 | 9 | class Fix2Chimera(object): 10 | def __init__(self, tmp_dir): 11 | self.tmp_dir = tmp_dir 12 | 13 | def fixreadname(self, chimeric_junction_file, output_file): 14 | # Because sometimes, for example -I flag of fastq-dump will add ".1" and ".2" read suffices. 15 | # "======== NOTE! ======= The default flag for matched pairedend reads is suffice '.1' and '.2'. " 16 | chimeric_junction = open(chimeric_junction_file, 'r') 17 | output = open(output_file, 'w') 18 | for line in chimeric_junction: 19 | # split field 10 20 | suffice = False 21 | s = [str(i).strip() for i in line.split('\t')] 22 | # print s 23 | if len(s[9].split('.')[-1]) == 1: 24 | suffice = True 25 | if suffice: 26 | s[9] = '.'.join(s[9].split('.')[:-1]) 27 | output.write('\t'.join(s)) 28 | else: 29 | output.write('\t'.join(s)) 30 | 31 | chimeric_junction.close() 32 | output.close() 33 | 34 | def fixmate2(self, chimeric_junction_mate2, output_file): 35 | # Fix the orientation of mate2 36 | 37 | if not os.path.isfile(chimeric_junction_mate2): 38 | sys.exit("ERROR: File " + str(chimeric_junction_mate2) + " is missing!") 39 | 40 | chimeric_junction = open(chimeric_junction_mate2, 'r') 41 | 42 | def modify_junctiontype(junctiontype): 43 | if junctiontype == '0': 44 | return '0' 45 | else: 46 | return str(3 - int(junctiontype)) 47 | 48 | linecnt = 1 49 | output = open(output_file, 'w') 50 | for line in chimeric_junction: 51 | line = line.rstrip() 52 | line_split = line.split('\t') 53 | 54 | if line_split[0] == "chr_donorA": 55 | continue 56 | # check if the row has all fields 57 | if len(line_split) < 14: 58 | print(("WARNING: File " + str(chimeric_junction_mate2) + ", line " + str(linecnt) 59 | + " does not contain all features.")) 60 | print(("WARNING: " + str(chimeric_junction_mate2) + " is probably corrupt.")) 61 | print(("WARNING: Offending line: " + str(line))) 62 | 63 | linecnt += 1 64 | 65 | if line_split[2] == '+': 66 | line_split[2] = '-' 67 | line_split[5] = '-' 68 | else: 69 | line_split[2] = '+' 70 | line_split[5] = '+' 71 | line_split[6] = modify_junctiontype(line_split[6]) 72 | output.write('\t'.join((line_split[0], line_split[4], line_split[2], line_split[3], line_split[1], 73 | line_split[5], line_split[6], line_split[7], line_split[8], line_split[9], 74 | line_split[10], line_split[11], line_split[12], line_split[13]))+'\n') 75 | 76 | chimeric_junction.close() 77 | output.close() 78 | 79 | def concatenatefiles(self, output_file, *fnames): 80 | import shutil 81 | destination = open(output_file, 'wb') 82 | for fname in fnames: 83 | if not os.path.isfile(fname): 84 | sys.exit("ERROR: File " + str(fname) + " is missing!") 85 | else: 86 | shutil.copyfileobj(open(fname, 'rb'), destination) 87 | destination.close() 88 | 89 | def fixchimerics(self, mate1, mate2, joined, output_file): 90 | # take chimeric.junction.out from two mate mapping and mate-joined mapping, 91 | # return fixed chimeric.out.junction 92 | 93 | # First, fix mate2 94 | self.fixmate2(mate2, mate2 + '.fixed') 95 | 96 | # Second, merge two mate files, select duplicates 97 | self.concatenatefiles(self.tmp_dir + 'tmp_merged', mate1, mate2 + '.fixed') # does not care if files are empty 98 | self.printduplicates(self.tmp_dir + 'tmp_merged', self.tmp_dir + 'tmp_twochimera', 99 | field=10) # TODO: field is static? 100 | 101 | if not os.path.isfile(self.tmp_dir + 'tmp_twochimera'): 102 | sys.exit("PE-independent mode selected but all corresponding junctions files are empty!") 103 | 104 | self.concatenatefiles(output_file, self.tmp_dir + 'tmp_twochimera', joined) 105 | 106 | def printduplicates(self, merged, duplicates, field=10): 107 | inputfile = None 108 | dup = None 109 | 110 | if not os.path.isfile(merged): 111 | sys.exit("ERROR: File " + str(merged) + " is missing!") 112 | elif os.stat(merged).st_size == 0: 113 | print(("WARNING: File " + str(merged) + " is empty!")) 114 | else: 115 | try: 116 | inputfile = open(merged, 'r') 117 | dup = open(duplicates, 'w') 118 | seen = dict() 119 | # check read name suffice 120 | suffice = False 121 | if len(inputfile.readline().split('\t')[field - 1].split('.')[-1]) == 1: 122 | suffice = True 123 | for line in inputfile: 124 | line_split = line.split('\t') 125 | if suffice: 126 | key = line_split[field - 1][:-2] 127 | else: 128 | key = line_split[field - 1] 129 | if key in seen: # has been added to dict 130 | if not seen[key][0]: # but it has not yet been set to True (already written) 131 | dup.write(seen[key][1]) # write the content of the key 132 | seen[key] = (True, seen[key][1]) # set key to seen and written 133 | dup.write(line) # write the complete original line to duplicate file 134 | else: 135 | seen[key] = (False, line) # executed when we see the read name first, sets false in dict 136 | finally: 137 | inputfile.close() 138 | dup.close() 139 | -------------------------------------------------------------------------------- /DCC/circFilter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import os 3 | import sys 4 | 5 | import HTSeq 6 | 7 | from .IntervalTree import IntervalTree 8 | 9 | 10 | ########################## 11 | # Input of this script # 12 | ########################## 13 | # This script input a count table: 14 | # chr start end junctiontype count1 count2 ... countn 15 | # and a repeatitive region file in gtf format 16 | # specify minimum circular RNA length 17 | 18 | 19 | class Circfilter(object): 20 | def __init__(self, length, countthreshold, replicatethreshold, tmp_dir): 21 | ''' 22 | counttable: the circular RNA count file, typically generated by findcircRNA.py: chr start end junctiontype count1 count2 ... countn 23 | rep_file: the gtf file to specify the region of repeatitive reagion of analyzed genome 24 | length: the minimum length of circular RNAs 25 | countthreshold: the minimum expression level of junction type 1 circular RNAs 26 | ''' 27 | # self.counttable = counttable 28 | # self.rep_file = rep_file 29 | self.length = int(length) 30 | # self.level0 = int(level0) 31 | self.countthreshold = int(countthreshold) 32 | # self.threshold0 = int(threshold0) 33 | self.replicatethreshold = int(replicatethreshold) 34 | self.tmp_dir = tmp_dir 35 | 36 | # Read circRNA count and coordinates information to numpy array 37 | def readcirc(self, countfile, coordinates): 38 | # Read the circRNA count file 39 | circ = open(countfile, 'r') 40 | coor = open(coordinates, 'r') 41 | count = [] 42 | indx = [] 43 | for line in circ: 44 | fields = line.split('\t') 45 | # row_indx = [str(itm) for itm in fields[0:4]] 46 | # print row_indx 47 | try: 48 | row_count = [int(itm) for itm in fields[4:]] 49 | except ValueError: 50 | row_count = [float(itm) for itm in fields[4:]] 51 | count.append(row_count) 52 | # indx.append(row_indx) 53 | 54 | for line in coor: 55 | fields = line.split('\t') 56 | row_indx = [str(itm).strip() for itm in fields[0:6]] 57 | indx.append(row_indx) 58 | 59 | count = np.array(count) 60 | indx = np.array(indx) 61 | circ.close() 62 | return count, indx 63 | 64 | # Do filtering 65 | def filtercount(self, count, indx): 66 | print('Filtering by read counts') 67 | sel = [] # store the passed filtering rows 68 | for itm in range(len(count)): 69 | if indx[itm][4] == '0': 70 | # if sum( count[itm] >= self.level0 ) >= self.threshold0: 71 | # sel.append(itm) 72 | pass 73 | elif indx[itm][4] != '0': 74 | if sum(count[itm] >= self.countthreshold) >= self.replicatethreshold: 75 | sel.append(itm) 76 | 77 | # splicing the passed filtering rows 78 | if len(sel) == 0: 79 | sys.exit("No circRNA passed the expression threshold filtering.") 80 | return count[sel], indx[sel] 81 | 82 | def read_rep_region(self, regionfile): 83 | regions = HTSeq.GFF_Reader(regionfile, end_included=True) 84 | rep_tree = IntervalTree() 85 | for feature in regions: 86 | iv = feature.iv 87 | rep_tree.insert(iv, annotation='.') 88 | return rep_tree 89 | 90 | def filter_nonrep(self, regionfile, indx0, count0): 91 | if not regionfile is None: 92 | rep_tree = self.read_rep_region(regionfile) 93 | 94 | def numpy_array_2_GenomiInterval(array): 95 | left = HTSeq.GenomicInterval(str(array[0]), int(array[1]), int(array[1]) + self.length, str(array[5])) 96 | right = HTSeq.GenomicInterval(str(array[0]), int(array[2]) - self.length, int(array[2]), str(array[5])) 97 | return left, right 98 | 99 | keep_index = [] 100 | for i, j in enumerate(indx0): 101 | out = [] 102 | left, right = numpy_array_2_GenomiInterval(j) 103 | rep_tree.intersect(left, lambda x: out.append(x)) 104 | rep_tree.intersect(right, lambda x: out.append(x)) 105 | if not out: 106 | # not in repetitive region 107 | keep_index.append(i) 108 | indx0 = indx0[keep_index] 109 | count0 = count0[keep_index] 110 | nonrep = np.column_stack((indx0, count0)) 111 | # write the result 112 | np.savetxt(self.tmp_dir + 'tmp_unsortedWithChrM', nonrep, delimiter='\t', newline='\n', fmt='%s') 113 | 114 | def dummy_filter(self, indx0, count0): 115 | nonrep = np.column_stack((indx0, count0)) 116 | # write the result 117 | np.savetxt(self.tmp_dir + 'tmp_unsortedWithChrM', nonrep, delimiter='\t', newline='\n', fmt='%s') 118 | 119 | def removeChrM(self, withChrM): 120 | print('Remove ChrM') 121 | unremoved = open(withChrM, 'r').readlines() 122 | removed = [] 123 | for lines in unremoved: 124 | if not lines.startswith('chrM') and not lines.startswith('MT'): 125 | removed.append(lines) 126 | removedfile = open(self.tmp_dir + 'tmp_unsortedNoChrM', 'w') 127 | removedfile.writelines(removed) 128 | removedfile.close() 129 | 130 | def sortOutput(self, unsorted, outCount, outCoordinates, samplelist=None): 131 | # Sample list is a string with sample names seperated by \t. 132 | # Split used to split if coordinates information and count information are integrated 133 | count = open(outCount, 'w') 134 | coor = open(outCoordinates, 'w') 135 | if samplelist: 136 | count.write('Chr\tStart\tEnd\t' + samplelist + '\n') 137 | lines = open(unsorted).readlines() 138 | for line in lines: 139 | linesplit = [x.strip() for x in line.split('\t')] 140 | count.write('\t'.join(linesplit[0:3] + list(linesplit[6:])) + '\n') 141 | coor.write('\t'.join(linesplit[0:6]) + '\n') 142 | coor.close() 143 | count.close() 144 | 145 | def remove_tmp(self): 146 | try: 147 | os.remove(self.tmp_dir + 'tmp_left') 148 | os.remove(self.tmp_dir + 'tmp_right') 149 | os.remove(self.tmp_dir + 'tmp_unsortedWithChrM') 150 | os.remove(self.tmp_dir + 'tmp_unsortedNoChrM') 151 | except OSError: 152 | pass 153 | -------------------------------------------------------------------------------- /DCC/CombineCounts.py: -------------------------------------------------------------------------------- 1 | # This script used to combine individual circRNA count files to a single count table 2 | 3 | # invoke with column nr to extract as first parameter followed by 4 | # file names. The files should all have the same number of rows 5 | 6 | import os 7 | import re 8 | import sys 9 | from collections import OrderedDict 10 | from copy import deepcopy 11 | 12 | 13 | class Combine(object): 14 | def __init__(self, tmp_dir): 15 | self.tmp_dir = tmp_dir 16 | 17 | def comb_coor(self, circfiles, strand=True): 18 | """ 19 | Combine coordinates of all samples to one. 20 | """ 21 | coordinates = open(self.tmp_dir + 'tmp_coordinates', 'w') 22 | # coors = set() 23 | coorsDict = {} # Use all except the strand and junction type information as key, to uniq the list. 24 | 25 | for files in circfiles: 26 | onefile = open(files, 'r') 27 | for lines in onefile: 28 | tmp = lines.split('\t') 29 | if strand: 30 | coorsDict[tmp[0] + '\t' + tmp[1] + '\t' + tmp[2] + '\t' + '.' + '\t' + tmp[5]] = '\t' + tmp[ 31 | 6] + '\t' + tmp[5] + '\n' 32 | else: 33 | coorsDict[tmp[0] + '\t' + tmp[1] + '\t' + tmp[2] + '\t' + '.' + '\t'] = tmp[6] + '\t' + tmp[ 34 | 5] + '\n' 35 | onefile.close() 36 | 37 | if strand: 38 | coors = ['\t'.join(key.split('\t')[:-1]) + value for key, value in coorsDict.items()] 39 | else: 40 | coors = ['{}{}'.format(key, value) for key, value in coorsDict.items()] 41 | 42 | coorsSorted = self.sortBed(coors, retList=True) 43 | for itm in coorsSorted: 44 | coordinates.write('\t'.join(itm)) 45 | 46 | def map(self, coordinates, filelist, strand=True, col=5): 47 | # type: (object, object, object, object) -> object 48 | # read coordinates 49 | mapto = OrderedDict() 50 | with open(coordinates) as coor: 51 | for lin in coor: 52 | line_split = lin.split('\t') 53 | if strand: 54 | mapto.setdefault(line_split[0] + line_split[1] + line_split[2] + line_split[5].strip('\n'), 55 | []).append(lin.strip('\n')) 56 | else: 57 | mapto.setdefault(line_split[0] + line_split[1] + line_split[2], []).append(lin.strip('\n')) 58 | 59 | for fname in filelist: 60 | run_mapto = deepcopy(mapto) 61 | with open(fname) as f: 62 | for lin in f: 63 | line_split = lin.split('\t') 64 | if strand: 65 | cor = line_split[0] + line_split[1] + line_split[2] + line_split[5].strip('\n') 66 | else: 67 | cor = line_split[0] + line_split[1] + line_split[2] 68 | run_mapto[cor].append(line_split[col - 1]) 69 | with open(fname + 'mapped', 'w') as fout: 70 | for key in run_mapto: 71 | if len(run_mapto[key]) == 1: 72 | run_mapto[key].append('0') 73 | fout.write('\t'.join(run_mapto[key]) + '\n') 74 | 75 | def deletefile(self, dirt, pattern): 76 | # First check whether the input is a list of files or a regular expression string 77 | if isinstance(pattern, str): 78 | # A list to store names of deleted files 79 | deleted = [] 80 | for f in os.listdir(dirt): 81 | if re.search(pattern, f): 82 | os.remove(os.path.join(dirt, f)) 83 | deleted.append(f) 84 | elif isinstance(pattern, list): 85 | for f in pattern: 86 | os.remove(os.path.join(dirt, f)) 87 | deleted = pattern 88 | return deleted 89 | 90 | def sortBed(self, bedfile, retList=False): 91 | # The input could be a list with one element per line of bedfile, or a file 92 | # First check whether the input is a list 93 | if isinstance(bedfile, list) or isinstance(bedfile, tuple) or isinstance(bedfile, set): 94 | bedfile = list(bedfile) 95 | # check dimension 96 | if isinstance(bedfile[0], list): 97 | # Sort 98 | bedfileSorted = sorted(bedfile, key=lambda x: (x[0], int(x[1]), int(x[2]), x[5])) 99 | else: 100 | # Split 101 | for indx, elem in enumerate(bedfile): 102 | bedfile[indx] = elem.split('\t') 103 | bedfileSorted = sorted(bedfile, key=lambda x: (x[0], int(x[1]), int(x[2]), x[5])) 104 | 105 | elif isinstance(bedfile, str): 106 | try: 107 | fileOpen = open(bedfile, 'r').readlines() 108 | for indx, elem in enumerate(fileOpen): 109 | fileOpen[indx] = elem.split('\t') 110 | except IOError: 111 | sys.exit('Input a quoted filename or a list.') 112 | else: 113 | bedfileSorted = sorted(fileOpen, key=lambda x: (x[0], int(x[1]), int(x[2]), x[5])) 114 | # Write to file 115 | if retList: 116 | pass 117 | else: 118 | output = open('bedfileSorted', 'w') 119 | output.writelines(bedfileSorted) 120 | else: 121 | sys.exit('Can only sort list, set, tuple or file') 122 | return bedfileSorted 123 | 124 | def combine(self, Alist, col=7, circ=True): 125 | # Alist is a list of files to be combined, either mapped circRNA or host gene counts 126 | col = int(col) 127 | res = {} 128 | 129 | for file_name in Alist: 130 | for line_nr, line in enumerate(open(file_name)): 131 | line_split = line.strip('\n').split('\t') 132 | 133 | if circ: # input are circRNA counts 134 | # check whether the fifth field has any number or empty, if empty, substitute with 0 135 | if line_split[col - 1] == '.': 136 | line_split[col - 1] = '0' 137 | # elif line_split[col-1] != '': 138 | # res.setdefault(line_nr,[]) will set res[line_nr]=[] if res does not have key 'line_nr', 139 | # when the key 'line_nr' exist, it will return the value which is a list [something], and will append the read count later 140 | # pass 141 | # elif len(line_split) != 5: 142 | # sys.exit("Number of fields in the individual count file is not correct.") 143 | res.setdefault(line_nr, ['\t'.join(line_split[:3]+[line_split[5]])]).append(line_split[col - 1]) 144 | 145 | else: # input are host gene counts 146 | res.setdefault(line_nr, ['\t'.join(line_split[:3])]).append(line_split[col - 1]) 147 | return res 148 | 149 | def writeouput(self, output, res, samplelist=None, header=False): 150 | # Sample list is a string with sample names seperated by \t. 151 | outfile = open(output, 'w') 152 | if header: 153 | outfile.write('Chr\tStart\tEnd\tStrand\t' + samplelist + '\n') 154 | for line_nr in sorted(res): 155 | outfile.write("%s\n" % '\t'.join(res[line_nr])) 156 | outfile.close() 157 | 158 | def writeouput_linear(self, output, res, samplelist=None, header=False): 159 | # Sample list is a string with sample names seperated by \t. 160 | outfile = open(output, 'w') 161 | if header: 162 | outfile.write('Chr\tStart\tEnd\t' + samplelist + '\n') 163 | for line_nr in sorted(res): 164 | outfile.write("%s\n" % '\t'.join(res[line_nr])) 165 | outfile.close() 166 | -------------------------------------------------------------------------------- /DCC/circAnnotate.py: -------------------------------------------------------------------------------- 1 | # This module annotates the circRNAs with gene names, and also filters 2 | # the circRNA candidates by requiring "CircRNA could not from more 3 | # than two annotated linear gene." 4 | 5 | import logging 6 | import os 7 | import re 8 | import warnings 9 | 10 | import HTSeq 11 | 12 | from .IntervalTree import IntervalTree 13 | 14 | 15 | class CircAnnotate(object): 16 | def __init__(self, tmp_dir, strand=True): 17 | self.strand = strand 18 | self.tmp_dir = tmp_dir 19 | 20 | def selectGeneGtf(self, gtf_file): 21 | # construct annotation tree 22 | # new_gtf file contains only exon annotation 23 | gtf = HTSeq.GFF_Reader(gtf_file, end_included=True) 24 | annotation_tree = IntervalTree() 25 | gtf_exon = [] 26 | for feature in gtf: 27 | # Select only exon line 28 | if feature.type == 'exon': 29 | gtf_exon.append(feature.get_gff_line().split('\t')) 30 | 31 | iv = feature.iv 32 | try: 33 | row = feature.attr 34 | row['type'] = feature.type 35 | except: 36 | row = feature.get_gff_line() 37 | 38 | annotation_tree.insert(iv, annotation=row) 39 | 40 | gtf_exon_sorted = sorted(gtf_exon, key=lambda x: (x[0], int(x[3]), int(x[4]))) 41 | gtf_exon_sorted = ['\t'.join(s) for s in gtf_exon_sorted] 42 | new_gtf = open(self.tmp_dir + "tmp_" + os.path.basename(gtf_file) + '.exon.sorted', 'w') 43 | new_gtf.writelines(gtf_exon_sorted) 44 | new_gtf.close() 45 | return annotation_tree 46 | 47 | def annotate_one_interval(self, interval, annotation_tree, what='gene'): 48 | out = [] 49 | annotation_tree.intersect(interval, lambda x: out.append(x.annotation)) 50 | annotation = self.searchGeneName(out, what=what) 51 | return annotation 52 | 53 | def annotate(self, circfile, annotation_tree, output): 54 | # the circRNA file should be in a bed format, have chr\tstart\tend\t'.'\tjunctiontype\tstrand 55 | # The annotation tree should be a IntervalTree object 56 | 57 | # check the input 58 | with open(circfile, 'r') as tmpcirc: 59 | tmpsplit = tmpcirc.readline().split('\t') 60 | if len(tmpsplit) != 6: 61 | warnings.warn('Input circRNA file is not the desired bed6 format!') 62 | logging.warning('Input circRNA file is not the desired bed6 format!') 63 | 64 | # Annotate with Interval tree algorithm 65 | out = open(output, 'w') 66 | circ_regions = HTSeq.BED_Reader(circfile) 67 | for circ in circ_regions: 68 | annotation = self.annotate_one_interval(circ.iv, annotation_tree, what='gene') 69 | out.write('\t'.join([circ.iv.chrom, str(circ.iv.start), str(circ.iv.end), annotation, str(int(circ.score)), 70 | circ.iv.strand]) + '\n') 71 | out.close() 72 | 73 | # self.printbycolumns('_tmp_DCC/tmp_AnnotatedUnsorted',output,order=[1,2,3,6,4,5]) 74 | # os.remove('_tmp_DCC/tmp_AnnotatedUnsorted') 75 | 76 | def uniqstring(self, strings, sep=','): 77 | string = set(strings.split(sep)) 78 | string = sep.join(string) 79 | return string 80 | 81 | def annotateregions(self, circfile, annotation_tree, output): 82 | # Annotate with regions (Exon, intron, intergenic) 83 | # create left and right circle bundary bedfiles: chr\tstart\tstart chr\tend\tend 84 | circ = open(circfile, 'r').readlines() 85 | new_CircCoordinates = open(output, 'w') 86 | new_CircCoordinates.write('Chr\tStart\tEnd\tGene\tJunctionType\tStrand\tStart-End Region\tOverallRegion\n') 87 | for line in circ: 88 | line_split = line.split('\t') 89 | iv_left = HTSeq.GenomicInterval(line_split[0], int(line_split[1]), int(line_split[1]) + 1, 90 | line_split[5].strip('\n')) 91 | iv_right = HTSeq.GenomicInterval(line_split[0], int(line_split[2]) - 1, int(line_split[2]), 92 | line_split[5].strip('\n')) 93 | iv_left_annotation = self.annotate_one_interval(iv_left, annotation_tree, what='region') 94 | if not iv_left_annotation: 95 | iv_left_annotation = '.' 96 | iv_right_annotation = self.annotate_one_interval(iv_right, annotation_tree, what='region') 97 | if not iv_right_annotation: 98 | iv_right_annotation = '.' 99 | overall_annotation = self.uniqstring(iv_left_annotation + ',' + iv_right_annotation) 100 | 101 | iv_left_annotation = self.readRegionAnnotate(iv_left_annotation) 102 | iv_right_annotation = self.readRegionAnnotate(iv_right_annotation) 103 | new_CircCoordinates.write(line.strip( 104 | '\n') + '\t' + iv_left_annotation + '-' + iv_right_annotation + '\t' + overall_annotation + '\n') 105 | new_CircCoordinates.close() 106 | 107 | def readRegionAnnotate(self, annotations): 108 | if 'exon' in annotations: 109 | return 'exon' 110 | elif len(annotations) > 1 and annotations != 'region' and annotations != 'not_annotated': 111 | return 'intron' 112 | elif annotations == 'not_annotated': 113 | return 'intergenic' 114 | 115 | def filtbygene(self, circ2filter, output): 116 | # This funtion filter the circs base on: circRNAs should not come from two genes. 117 | out = open(output, 'w') 118 | with open(circ2filter, 'r') as circ: 119 | for line in circ: 120 | tmp = line.split('\t') 121 | n = tmp[3].split(',') 122 | try: 123 | if len(n) == 1: 124 | out.write(line) 125 | except IndexError: 126 | pass 127 | out.close() 128 | 129 | def printbycolumns(self, fileIn, fileOut, order=[], sep='\t', fillempty=True): 130 | tmpIn = open(fileIn, 'r') 131 | tmpOut = open(fileOut, 'w') 132 | for lines in tmpIn: 133 | tmpsplit = [x.strip() for x in lines.split(sep)] 134 | if fillempty: 135 | tmpsplit = ['.' if x == '' else x for x in tmpsplit] 136 | # Get gene_id or gene_name annotation 137 | tmpsplit[5] = self.searchGeneName(tmpsplit[5]) 138 | tmpOut.write('\t'.join([tmpsplit[int(i) - 1] for i in order]) + '\n') 139 | tmpIn.close() 140 | tmpOut.close() 141 | 142 | def searchGeneName1(self, annotations): 143 | # Search for gene_name in gtf annotation, if gene_name cannot be found, look for gene_id 144 | # example: gene_id "ENSG00000187634"; gene_name "SAMD11"; gene_source "ensembl_havana"; gene_biotype "lincRNA"; 145 | ann = ','.join(list(set(re.findall(r'gene_name\=?\s?"([^;]*)"\;', annotations)))) 146 | if len(ann) == 0: 147 | # Look for "gene=", which is used in gff3 format 148 | ann = ','.join(list(set(re.findall(r'gene\=?\s?"([^;]*)"\;', annotations)))) 149 | if len(ann) == 0: 150 | # Look for gene_id 151 | ann = ','.join(list(set(re.findall(r'gene_id\=?\s?"([^;]*)"\;', annotations)))) 152 | if len(ann) == 0: 153 | # Look for transcript_id 154 | ann = ','.join(list(set(re.findall(r'transcript_id\=?\s?"([^;]*)"\;', annotations)))) 155 | if len(ann) == 0: 156 | ann = 'N/A' 157 | return ann 158 | 159 | def searchGeneName(self, annotations, what='gene'): 160 | if what == 'gene': 161 | collect = set() 162 | for annotation in annotations: 163 | # Search for gene_name which is used by ensembl gtf annotation 164 | try: 165 | gene = annotation['gene_name'] 166 | except TypeError: 167 | gene = self.searchGeneName1(annotation) 168 | except KeyError: 169 | # Search for gene, which might used in GFF annotation 170 | try: 171 | gene = annotation['gene'] 172 | except: 173 | # Search for gene_id 174 | try: 175 | gene = annotation['gene_id'] 176 | except: 177 | try: 178 | gene = annotation['transcript_id'] 179 | except: 180 | gene = 'N/A' 181 | collect.add(gene) 182 | # Collapse all genes together 183 | if len(collect) > 1: 184 | try: 185 | collect.remove('N/A') 186 | except KeyError: 187 | pass 188 | else: 189 | # annotate region 190 | collect = set() 191 | for annotation in annotations: 192 | try: 193 | gene = annotation['type'] 194 | except TypeError: 195 | gene = annotation.split('\t')[2] 196 | except: 197 | gene = 'N/A' 198 | collect.add(gene) 199 | genes = ','.join(collect) 200 | if not genes: 201 | # empty string 202 | genes = 'not_annotated' 203 | 204 | return genes 205 | -------------------------------------------------------------------------------- /DCC/findcircRNA.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | import collections 4 | import logging 5 | import re 6 | 7 | 8 | class Findcirc(object): 9 | # Initialize some parameters 10 | def __init__(self, endTol, minL, maxL): 11 | # self.strand = strand 12 | self.endTol = endTol 13 | # self.output = output 14 | self.maxL = int(maxL) 15 | self.minL = int(minL) 16 | 17 | # self.findcirc(Chim_junc) 18 | 19 | def cigarGenomicDist(self, cig): 20 | C = re.findall('[a-zA-Z]', cig) 21 | L = re.findall('\-?[0-9]+', cig) 22 | n = len(L) 23 | g = 0 24 | for i in range(0, n): 25 | if C[i] != 'S' and C[i] != "I": 26 | g = g + int(L[i]) 27 | return g 28 | 29 | def printcircline(self, Chim_junc, output): 30 | junctionfile = open(Chim_junc, 'r') 31 | outfile = open(output, 'w') 32 | for line in junctionfile: 33 | L = line.split('\t') 34 | if L[0] == "chr_donorA": 35 | continue 36 | if int(L[6]) >= 0 and L[0] == L[3] and L[2] == L[5] and ( 37 | (L[2] == '-' and int(L[4]) > int(L[1]) and self.minL < (int(L[4]) - int(L[1])) < self.maxL) or ( 38 | L[2] == '+' and int(L[1]) > int(L[4]) and self.minL < ( 39 | int(L[1]) - int(L[4])) < self.maxL)): 40 | if (L[2] == '+' and (int(L[10]) + self.endTol) > int(L[4]) and ( 41 | int(L[12]) + self.cigarGenomicDist(L[13]) - self.endTol) <= int(L[1])) or ( 42 | L[2] == '-' and (int(L[12]) + self.endTol) > int(L[1]) and ( 43 | int(L[10]) + self.cigarGenomicDist(L[11]) - self.endTol) <= int(L[4])): 44 | outfile.write(line) 45 | outfile.close() 46 | junctionfile.close() 47 | 48 | # The bug here is: sepDuplicates, all the duplicates come from two mates are chimera, no problem, 49 | # but the nonduplicates not all from joined mapping. For some reason, some reads chimerically mapped separately, 50 | # but not jointly, although they are not two mates chimeria 51 | 52 | def sepDuplicates(self, Chim_junc, duplicates, nonduplicates): 53 | # seperate out duplicated reads, means both mates are chimera 54 | # Chim_junc is the output of printcircline function 55 | # Duplicated reads are appear in a scrambled order, the real strand read come later than the reversed strand 56 | 57 | junctionfile = open(Chim_junc, 'r') 58 | dup = open(duplicates, 'w') 59 | nondup = open(nonduplicates, 'w') 60 | 61 | reads = [] 62 | lines = [] # A list of all lines 63 | suffice = False 64 | for line in junctionfile: 65 | line_split = line.split('\t') 66 | if not suffice: 67 | if len(line_split[9].split('.')[-1]) == 1: 68 | suffice = True 69 | if suffice: 70 | readname = '.'.join( 71 | (line_split[1], line_split[2], line_split[4], '.'.join(line_split[9].split('.')[:-1]))) 72 | else: 73 | readname = '.'.join((line_split[1], line_split[2], line_split[4], line_split[9])) 74 | reads.append(readname) 75 | lines.append(line) 76 | 77 | for indx, read in enumerate(reads): 78 | if reads.count(read) == 2: 79 | dup.write(lines[indx]) 80 | elif reads.count(read) > 2: 81 | print('Read %s has more than 2 count.' % read) 82 | try: 83 | logging.warning('Read %s has more than 2 count.' % read) 84 | except NameError: 85 | pass 86 | else: 87 | nondup.write(lines[indx]) 88 | 89 | junctionfile.close() 90 | dup.close() 91 | nondup.close() 92 | 93 | def smallcirc(self, duplicates, output, strand=True): 94 | ''' 95 | Find small circRNAs in paired-end data where both mates are chimeric. Input is duplicates file by sepDuplicates. 96 | ''' 97 | 98 | # The second occure read has the 'real' strand of that circle. 99 | 100 | dup = open(duplicates).readlines() 101 | outfile = open(output, 'w') 102 | 103 | collect = [] 104 | for line in dup: 105 | L = line.split('\t') 106 | if L[2] == '+': 107 | identifier = (L[0], L[1], L[3], L[4], L[9]) 108 | elif L[2] == '-': 109 | identifier = (L[0], L[4], L[3], L[1], L[9]) 110 | # print identifier 111 | if identifier in collect: 112 | if L[2] == '+': 113 | if strand: 114 | if L[6] == '0': 115 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), '-', '0', L[7], L[8]] 116 | else: 117 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), '-', str(3 - int(L[6])), L[7], L[8]] 118 | outfile.write(('\t').join(res) + '\n') 119 | else: 120 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), L[2], L[6], L[7], L[8]] 121 | outfile.write(('\t').join(res) + '\n') 122 | if L[2] == '-': 123 | if strand: 124 | if L[6] == '0': 125 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), '+', '0', L[7], L[8]] 126 | else: 127 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), '+', str(3 - int(L[6])), L[7], L[8]] 128 | outfile.write(('\t').join(res) + '\n') 129 | else: 130 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), L[2], L[6], L[7], L[8]] 131 | outfile.write(('\t').join(res) + '\n') 132 | else: 133 | collect.append(identifier) # Identifiers for duplicates 134 | 135 | ## All switch to plus strand 136 | # if L[2] == '-': 137 | # collect.append((L[0],L[4],'+',L[3],L[1],'+',L[9])) 138 | # else: 139 | # collect.append(tuple(L[0:6]+[L[9]])) 140 | # 141 | # for line in dup: 142 | # # Only print out with '+' strand 143 | # L = line.split('\t') 144 | # toTest = tuple(L[0:6]+[L[9]]) 145 | # if collect.count(toTest) == 2: 146 | # #res = line 147 | # res = [L[0],L[4],L[1],L[2],L[6],L[7],L[8]] 148 | # outfile.write(('\t').join(res) + '\n') 149 | # #outfile.write(res) 150 | 151 | outfile.close() 152 | 153 | def findcirc(self, Chim_junc, output, strand=True): 154 | junctionfile = open(Chim_junc, 'r') 155 | outfile = open(output, 'w') 156 | linecnt = 1 157 | for line in junctionfile: 158 | L = line.split('\t') 159 | linecnt = linecnt + 1 160 | 161 | if len(L) < 14: 162 | print(("WARNING: File " + str(Chim_junc) + ", line " + str(linecnt) + " does not contain all features.")) 163 | print(("WARNING: " + str(Chim_junc) + " is probably corrupt.")) 164 | if L[0] == "chr_donorA": 165 | continue 166 | if int(L[6]) >= 0 and L[0] == L[3] and L[2] == L[5] and ( 167 | (L[2] == '-' and int(L[4]) > int(L[1]) and self.minL < (int(L[4]) - int(L[1])) < self.maxL) or ( 168 | L[2] == '+' and int(L[1]) > int(L[4]) and self.minL < ( 169 | int(L[1]) - int(L[4])) < self.maxL)): 170 | if (L[2] == '+' and (int(L[10]) + self.endTol) > int(L[4]) and ( 171 | int(L[12]) + self.cigarGenomicDist(L[13]) - self.endTol) <= int(L[1])): 172 | if strand: 173 | if L[6] == '0': 174 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), '-', '0', L[7], L[8]] 175 | else: 176 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), '-', str(3 - int(L[6])), L[7], L[8]] 177 | outfile.write(('\t').join(res) + '\n') 178 | else: 179 | res = [L[0], str(int(L[4]) + 1), str(int(L[1]) - 1), L[2], L[6], L[7], L[8]] 180 | outfile.write(('\t').join(res) + '\n') 181 | if L[2] == '-' and (int(L[12]) + self.endTol) > int(L[1]) and ( 182 | int(L[10]) + self.cigarGenomicDist(L[11]) - self.endTol) <= int(L[4]): 183 | if strand: 184 | if L[6] == '0': 185 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), '+', '0', L[7], L[8]] 186 | else: 187 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), '+', str(3 - int(L[6])), L[7], L[8]] 188 | outfile.write(('\t').join(res) + '\n') 189 | else: 190 | res = [L[0], str(int(L[1]) + 1), str(int(L[4]) - 1), L[2], L[6], L[7], L[8]] 191 | outfile.write(('\t').join(res) + '\n') 192 | outfile.close() 193 | junctionfile.close() 194 | 195 | 196 | class Sort(object): 197 | def __init__(self): 198 | """ 199 | The Findcirc_output option takes the output of Class Findcirc. 200 | Output is the sorted and bed format table with read counts information. 201 | """ 202 | # self.strand=strand 203 | # self.Findcirc_output=open(Findcirc_output,'r').readlines() 204 | # self.output=output 205 | # self.sort_count(self.Findcirc_output) 206 | 207 | def count(self, sortedlist, strand=True): 208 | """ 209 | This function takes a sorted list of circRNAs, will be called by function circ_sort, 210 | count each circRNAs and return a bed format count table 211 | """ 212 | cnt = collections.Counter() 213 | tmp_count = [] # store the bed format count circRNA count, but duplicated lines are not yet removed 214 | for itm in sortedlist: 215 | if strand: 216 | circs = (itm[0], itm[1], itm[2], itm[3]) 217 | elif not strand: 218 | circs = (itm[0], itm[1], itm[2]) 219 | else: 220 | print("Please specify correct strand information.") 221 | cnt[circs] += 1 222 | itm.append(str(cnt[circs])) 223 | # tmp_count.append( [itm[0],itm[1],itm[2],itm[3],itm[7],itm[4],itm[5],itm[6]] ) 224 | tmp_count.append([itm[0], itm[1], itm[2], '.', itm[7], itm[3], itm[4], itm[5], itm[6]]) 225 | # reverse the order of tmp_count, so when remove duplicates, the one counted all the counts 226 | tmp_count.reverse() 227 | # remove duplicated lines 228 | tmp_count_dedup = [] 229 | lines_seen = set() # holds the lines already seen 230 | for itm in tmp_count: 231 | if strand: 232 | tmp_itm = tuple((itm[0], itm[1], itm[2], itm[5])) 233 | elif not strand: 234 | tmp_itm = tuple((itm[0], itm[1], itm[2])) 235 | if tmp_itm not in lines_seen: 236 | tmp_count_dedup.append(itm) 237 | lines_seen.add(tmp_itm) 238 | # return the deduplicated count table (list) 239 | tmp_count_dedup.reverse() 240 | return tmp_count_dedup 241 | 242 | def sort_count(self, findcircOut, output, strand=True): 243 | # Equal to sort command in linux 244 | # file_list is the object of file read by readlines() 245 | file_list = open(findcircOut, 'r').readlines() 246 | output = open(output, 'w') 247 | tmp_sort = [] 248 | for itm in file_list: 249 | line_tmp = itm.strip().split('\t') 250 | tmp_sort.append(line_tmp) 251 | tmp_sorted = sorted(tmp_sort, key=lambda x: (x[0], int(x[1]), int(x[2]), x[5])) 252 | sorted_count = self.count(tmp_sorted, strand=strand) 253 | output.writelines('\t'.join(j) + '\n' for j in sorted_count) 254 | output.close() 255 | -------------------------------------------------------------------------------- /DCC/genecount.py: -------------------------------------------------------------------------------- 1 | # This module count the host gene counts 2 | # Required: pysam 3 | # Input: circRNA coordinates 4 | # aligned bam files 5 | # reference sequence 6 | # 7 | # coor: coordinates 8 | # rs: result 9 | 10 | import logging 11 | import random 12 | import string 13 | import sys 14 | import time 15 | 16 | import pysam 17 | 18 | 19 | class Genecount(object): 20 | def __init__(self, tmp_dir): 21 | self.tmp_dir = tmp_dir 22 | 23 | 24 | def id_generator(self, size=6, chars=string.ascii_uppercase + string.digits): 25 | return "".join(random.choice(chars) for _ in range(size)) 26 | 27 | 28 | def countmapped(self, string): 29 | # This function takes the 5th column (a string with mapping information), 30 | # and return the count of '.' and ','. Which are mapped read count 31 | 32 | rs = string.count(',') + string.count('.') 33 | 34 | return str(rs) 35 | 36 | 37 | def countspliced(self, string): 38 | # return the count of '>' and '<' 39 | rs = string.count('>') + string.count('<') 40 | return str(rs) 41 | 42 | 43 | def getreadscount(self, mpileup, countmapped=False): 44 | # Input a mpileup result, which is a list 45 | # The count information is in the 5th column 46 | # count the number of mapped reads represented by ',' and '.' or, spliced reads 47 | # represented by the number of '>' and '<' in the string 48 | 49 | count = [] 50 | 51 | # print "mpileup is a " + str(type(mpileup)) 52 | 53 | if type(mpileup) is str: 54 | 55 | mpileupline = mpileup.split('\n') 56 | 57 | for itm in mpileupline: 58 | tmp = itm.split('\t') 59 | 60 | if countmapped: 61 | if len(tmp) == 6: 62 | count.append(tmp[0] + '\t' + tmp[1] + '\t' + self.countmapped(tmp[4])) 63 | else: 64 | if len(tmp) == 6: 65 | count.append(tmp[0] + '\t' + tmp[1] + '\t' + self.countspliced(tmp[4])) 66 | 67 | elif type(mpileup) is list: 68 | 69 | for itm in mpileup: 70 | 71 | if countmapped: 72 | if len(mpileup) == 6: 73 | count.append(itm[0] + '\t' + itm[1] + '\t' + self.countmapped(itm[4])) 74 | else: 75 | if len(mpileup) == 6: 76 | count.append(itm[0] + '\t' + itm[1] + '\t' + self.countspliced(itm[4])) 77 | 78 | return count 79 | 80 | 81 | def genecount(self, circ_coordinates, bamfile, ref, tid): 82 | """ 83 | @circ_coordinates: quoted string, content with format "chr1\tstart\tend" 84 | @bamfile: quoted string 85 | @ref: quoted string 86 | """ 87 | 88 | # process the circ_coordinates to left circ position and right circ position 89 | coordinates = open(circ_coordinates, 'r').readlines()[1:] 90 | start_coordinates = open(self.tmp_dir + 'tmp_start_coordinates_' + tid, 'w') 91 | end_coordinates = open(self.tmp_dir + 'tmp_end_coordinates_' + tid, 'w') 92 | 93 | for line in coordinates: 94 | tmp = line.split('\t') 95 | start_coordinates.write(tmp[0] + '\t' + tmp[1] + '\n') 96 | end_coordinates.write(tmp[0] + '\t' + tmp[2] + '\n') 97 | 98 | # close position files: 99 | start_coordinates.close() 100 | end_coordinates.close() 101 | 102 | print(('Started linear gene expression counting for %s' % bamfile)) 103 | 104 | start = time.time() 105 | # mpileup get the read counts of the start and end positions 106 | print(("\t=> running mpileup for start positions [%s]" % bamfile)) 107 | mpileup_start = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_start_coordinates_' + tid) 108 | end = time.time() - start 109 | print(("\t=> mpileup for start positions for %s took %d seconds" % (bamfile, end))) 110 | 111 | start = time.time() 112 | # mpileup get the read counts of the start and end positions 113 | print(("\t=> running mpileup for end positions [%s]" % bamfile)) 114 | mpileup_end = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_end_coordinates_' + tid) 115 | end = time.time() - start 116 | print(("\t=> mpileup for end positions for %s took %d seconds" % (bamfile, end))) 117 | 118 | print("\t=> gathering read counts for start positions [%s]" % bamfile) 119 | startcount = self.getreadscount(mpileup_start, countmapped=True) 120 | 121 | print("\t=> gathering read counts for end positions [%s]" % bamfile) 122 | endcount = self.getreadscount(mpileup_end, countmapped=True) 123 | 124 | # remove tmp files 125 | # os.remove(self.tmp_dir + 'tmp_start_coordinates_' + tid) 126 | # os.remove(self.tmp_dir + 'tmp_end_coordinates_' + tid) 127 | 128 | print('Finished linear gene expression counting for %s' % bamfile) 129 | 130 | return startcount, endcount 131 | 132 | 133 | def submpileup(self, mpileup1, mpileup2, left=True): 134 | # Genome region: mpileup1 < mpileup2 135 | # used to calculate the spliced read counts difference 136 | # Input mpileup is the result of getreadscount function. 137 | # Input in a list of elements with format str\tstr\tstr 138 | new_mpileup = [] 139 | # need to consider that mpileup1 and mpileup2 are not the same length 140 | if len(mpileup1) == len(mpileup2): 141 | for itm in range(len(mpileup1)): 142 | mpileup1_count = int(mpileup1[itm].split('\t')[2]) 143 | mpileup2_count = int(mpileup2[itm].split('\t')[2]) 144 | shift = mpileup1_count - mpileup2_count 145 | if shift < 0: 146 | shift = 0 147 | new_mpileup.append( 148 | mpileup1[itm].split('\t')[0] + '\t' + mpileup1[itm].split('\t')[1] + '\t' + str(shift)) 149 | else: 150 | mpileup1_dict = {} 151 | mpileup2_dict = {} 152 | for itm in mpileup1: 153 | mpileup1_dict[(itm.split('\t')[0] + '\t' + itm.split('\t')[1])] = int(itm.split('\t')[2]) 154 | for itm in mpileup2: 155 | mpileup2_dict[(itm.split('\t')[0] + '\t' + str(int(itm.split('\t')[1]) - 1))] = int(itm.split('\t')[2]) 156 | 157 | for itm in mpileup1_dict: 158 | if itm in mpileup2_dict: 159 | if left: 160 | shift = mpileup1_dict[itm] - mpileup2_dict[itm] 161 | if shift < 0: 162 | shift = 0 163 | new_mpileup.append( 164 | itm.split('\t')[0] + '\t' + str(int(itm.split('\t')[1]) + 1) + '\t' + str(shift)) 165 | else: 166 | shift = mpileup2_dict[itm] - mpileup1_dict[itm] 167 | if shift < 0: 168 | shift = 0 169 | new_mpileup.append(itm.split('\t')[0] + '\t' + itm.split('\t')[1] + '\t' + str(shift)) 170 | 171 | return new_mpileup 172 | 173 | def linearsplicedreadscount(self, circ_coor, bamfile, ref, header=True): 174 | # Count linear spliced reads 175 | # process the circ_coordinates to left circ position and right circ position 176 | if header: 177 | coor = open(circ_coor, 'r').readlines()[1:] 178 | else: 179 | coor = open(circ_coor, 'r').readlines() 180 | start_coor = open(self.tmp_dir + 'tmp_start_coor', 'w') 181 | start_coor_1 = open(self.tmp_dir + 'tmp_start_coor_1', 'w') 182 | end_coor = open(self.tmp_dir + 'tmp_end_coor', 'w') 183 | end_coor_1 = open(self.tmp_dir + 'tmp_end_coor_1', 'w') 184 | 185 | for line in coor: 186 | tmp = line.split('\t') 187 | start_coor.write(tmp[0] + '\t' + tmp[1] + '\n') 188 | start_coor_1.write(tmp[0] + '\t' + str(int(tmp[1]) - 1) + '\n') 189 | end_coor.write(tmp[0] + '\t' + tmp[2] + '\n') 190 | end_coor_1.write(tmp[0] + '\t' + str(int(tmp[2]) + 1) + '\n') 191 | 192 | # close position files: 193 | start_coor.close() 194 | start_coor_1.close() 195 | end_coor.close() 196 | end_coor_1.close() 197 | print(('Started linear spliced read counting for %s' % bamfile)) 198 | 199 | # mpileup get the number of spliced reads at circle start position and (start-1) position. 200 | 201 | print(("\t=> running mpileup 1 for start positions [%s]" % bamfile)) 202 | mpileup_start = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_start_coor_1') 203 | 204 | print(("\t=> running mpileup 2 for start positions [%s]" % bamfile)) 205 | mpileup_start_1 = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_start_coor_2') 206 | 207 | # mpileup get the number of spliced reads at circle end position and (end+1) position. 208 | print(("\t=> running mpileup 1 for end positions [%s]" % bamfile)) 209 | mpileup_end = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_end_coor_1') 210 | 211 | print(("\t=> running mpileup 2 for end positions [%s]" % bamfile)) 212 | mpileup_end_1 = pysam.mpileup(bamfile, '-f', ref, '-l', self.tmp_dir + 'tmp_end_coor_2') 213 | 214 | # get count 215 | 216 | print("\t=> gathering read counts for start positions [%s]" % bamfile) 217 | startcount = self.submpileup(self.getreadscount(mpileup_start_1), self.getreadscount(mpileup_start)) 218 | 219 | print("\t=> gathering read counts for end positions [%s]" % bamfile) 220 | endcount = self.submpileup(self.getreadscount(mpileup_end), self.getreadscount(mpileup_end_1), left=False) 221 | 222 | # remove tmp files 223 | # os.remove(self.tmp_dir + 'tmp_start_coor') 224 | # os.remove(self.tmp_dir + 'tmp_start_coor_1') 225 | # os.remove(self.tmp_dir + 'tmp_end_coor') 226 | # os.remove(self.tmp_dir + 'tmp_end_coor_1') 227 | 228 | print('Finished linear spliced read counting for %s' % bamfile) 229 | 230 | return startcount, endcount 231 | 232 | def comb_gen_count(self, circ_coor, bamfile, ref, output, countlinearsplicedreads=True): 233 | idx = open(circ_coor, 'r').readlines()[1:] # make sure are tab delimited 234 | 235 | tid = self.id_generator() 236 | 237 | # tmp_start = open(options.startfile,'r') # make sure are tab delimited 238 | # tmp_end = open(options.endfile,'r') # make sure are taa delimited 239 | 240 | # This is the chromosome name and start position of the original bed file list, like Lvr_F_104_filtered_candid 241 | coordinates_indx_start = [] 242 | 243 | # This is the chromosome name and end position of the original bed file list, like Lvr_F_104_filtered_candid 244 | coordinates_indx_end = [] 245 | 246 | # This is the chromosome name and start position of the counted read counts bed file list, 247 | # like tmp_readcounts_start 248 | coordinates_start = {} 249 | 250 | # This is the chromosome name and start position of the counted read counts bed file list, 251 | # like tmp_readcounts_end 252 | coordinates_end = {} 253 | 254 | # Store the read counts of start positions 255 | count_start = [] 256 | 257 | # Store the read counts of the end positions 258 | count_end = [] 259 | 260 | # Store chr, start, end information from circRNAs candidates file 261 | coordinates = [] 262 | 263 | if countlinearsplicedreads: 264 | tmp_start, tmp_end = self.linearsplicedreadscount(circ_coor, bamfile, ref) 265 | else: 266 | # call genecount to get the start and end positon read counts 267 | tmp_start, tmp_end = self.genecount(circ_coor, bamfile, ref, tid) 268 | 269 | print('Ended linear gene expression counting %s' % bamfile) 270 | logging.info('Ended linear gene expression counting %s' % bamfile) 271 | 272 | for line in tmp_start: 273 | tmp_start_split = line.split('\t') 274 | coordinates_start[(tmp_start_split[0], tmp_start_split[1])] = tmp_start_split[2].strip() 275 | 276 | for line in tmp_end: 277 | tmp_end_split = line.split('\t') 278 | coordinates_end[(tmp_end_split[0], tmp_end_split[1])] = tmp_end_split[2].strip() 279 | 280 | for line in idx: 281 | indx_split = line.split('\t') 282 | coordinates_indx_start.append((indx_split[0], indx_split[1])) 283 | coordinates_indx_end.append((indx_split[0], indx_split[2].strip('\n'))) 284 | coordinates.append((indx_split[0], indx_split[1], indx_split[2].strip('\n'))) 285 | 286 | for itm in coordinates_indx_start: 287 | if itm in coordinates_start: 288 | count_start.append(coordinates_start[itm]) 289 | else: 290 | count_start.append('0') 291 | logging.info( 292 | 'WARNING: circRNA start position ' + str(itm) + ' does not have mapped read counts, treated as 0') 293 | 294 | for itm in coordinates_indx_end: 295 | if itm in coordinates_end: 296 | count_end.append(coordinates_end[itm]) 297 | else: 298 | count_end.append('0') 299 | logging.info( 300 | 'WARNING: circRNA end position ' + str(itm) + ' does not have mapped read counts, treated as 0') 301 | 302 | # write count table 303 | count_table = open(output, 'w') 304 | if len(coordinates) == len(count_start) == len(count_end): 305 | for i in range(len(coordinates)): 306 | res = list(coordinates[i]) + [count_start[i], count_end[i], 307 | str(int(round(float(count_start[i]) + float(count_end[i])) / 2))] 308 | count_table.write(('\t').join(res) + '\n') 309 | else: 310 | sys.exit('read count number does not match with number of circRNAs candidates') 311 | 312 | # close files 313 | # tmp_start.close() 314 | # tmp_end.close() 315 | count_table.close() 316 | 317 | print('Ended post processing %s' % bamfile) 318 | logging.info('Ended post processing %s' % bamfile) 319 | return tid 320 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ***************************************** 2 | DCC: detect circRNAs from chimeric reads 3 | ***************************************** 4 | 5 | DCC is a python package intended to detect and quantify circRNAs with high specificity. DCC works with the STAR (Dobin et al., 2013) ``chimeric.out.junction`` 6 | files which contains chimerically aligned reads including circRNA junction spanning reads. 7 | 8 | ****************************************** 9 | Installation 10 | ****************************************** 11 | 12 | 13 | DCC depends on pysam, pandas, numpy, and HTSeq. The installation process of DCC will automatically check for the dependencies and install or update missing (Python) packages. Different installation options are available: 14 | 15 | 1) Download the latest stable `DCC release `_ 16 | 17 | .. code-block:: bash 18 | 19 | $ tar -xvf DCC-.tar.gz 20 | 21 | $ cd DCC- 22 | 23 | $ python setup.py install --user 24 | 25 | 2) git clone 26 | 27 | .. code-block:: bash 28 | 29 | $ git clone https://github.com/dieterich-lab/DCC.git 30 | 31 | $ cd DCC 32 | 33 | $ python setup.py install --user 34 | 35 | Check the installation: 36 | 37 | .. code-block:: bash 38 | 39 | $ DCC --version 40 | 41 | If the Python installation binary path [e.g. $HOME/.local/bin for Ubuntu] is not included in your path, it is also possible run DCC directly: 42 | 43 | .. code-block:: bash 44 | 45 | $ python /scripts/DCC 46 | 47 | or even 48 | 49 | $ python /DCC/main.py 50 | 51 | 52 | ****************************************** 53 | Usage 54 | ****************************************** 55 | 56 | The detection of circRNAs from RNAseq data through DCC can be summarised in three steps: 57 | 58 | - Mapping of RNAseq data from quality checked fastq files. For paired-end (PE) data it is recommended to map the pair jointly and separately. The reason is that STAR does not output reads or read pairs that contain more than one chimeric junction. 59 | 60 | - Prepare the input files required by DCC. In summary, only one file is mandatory: ``samplesheet``, which specifies the locations for the ``chimeric.out.junction`` files (one relative or absolute path per line). [Command line flag: ``@samplesheet``] 61 | 62 | - A GTF format annotation of repetitive regions which is used to filter out circRNA candidates from repetitive regions. [Command line flag: ``-R your_repeat_file.gtf``] 63 | 64 | - For paired-end sequencing two files, e.g. ``mate1`` and ``mate2`` which contain the paths to the ``chimeric.out.junction`` files originating from the separate mate mapping step. [Command line flags: ``-m1 mate1file`` and ``-m2 mate2file``] 65 | 66 | - You may specify the location of the BAM files via the -B flag otherwise DCC tries to guess their location based on the supplied ``chimeric.out.junction`` paths. [Command line flag: ``-B @bam_file_list``] 67 | 68 | - DCC requires the ``SJ.out.tab`` files generated by STAR. DCC assumes they are located in the same folder as the BAM files and also retain their ``SJ.out.tab``. 69 | 70 | - DCC can be used to process circular RNA detection and host gene expression detection either in a one-pass strategy or might be used for only one part of the analysis: 71 | 72 | - Detect circRNAs and host gene expression: specify ``-D`` and ``-G`` option 73 | - Detect circRNAs only: ``-D`` 74 | - Detect host gene expression only: ``-G`` 75 | 76 | 77 | ****************************************** 78 | Step by step tutorial with sample data set 79 | ****************************************** 80 | 81 | In this tutorial, we use the data set from `Westholm et al. 2014 `_ as an example. The data are paired-end, stranded RiboMinus RNAseq data from *Drosophila melanogaster*, consisting of samples of 3 developmental stages (1 day, 4 days, and 20 days) collected from the heads. You can download the data from the NCBI SRA (accession number `SRP001696 `_). 82 | 83 | Mapping of the fastq files with `STAR `_ 84 | =========================================================================== 85 | 86 | Note: ``--alignSJoverhangMin`` and ``--chimJunctionOverhangMin`` should use the same value to make the circRNA expression and linear gene expression level comparable. 87 | 88 | * In a first step the paired-end data is mapped by using both mates. If the data is paired-end, an additional separate mate mapping is recommended (while not mandatory, this step will increase the sensitivity due to the the processing of small circular RNAs with only one chimeric junction point at each read mate). If the data is single-end, only this mapping step is required. In case of the Westholm data however, paired-end sequencing data is available. 89 | 90 | .. code-block:: bash 91 | 92 | $ mkdir Sample1 93 | $ cd Sample1 94 | $ STAR --runThreadN 10 \ 95 | --genomeDir [genome] \ 96 | --outSAMtype BAM SortedByCoordinate \ 97 | --readFilesIn Sample1_1.fastq.gz Sample1_2.fastq.gz \ 98 | --readFilesCommand zcat \ 99 | --outFileNamePrefix [sample prefix] \ 100 | --outReadsUnmapped Fastx \ 101 | --outSJfilterOverhangMin 15 15 15 15 \ 102 | --alignSJoverhangMin 15 \ 103 | --alignSJDBoverhangMin 15 \ 104 | --outFilterMultimapNmax 20 \ 105 | --outFilterScoreMin 1 \ 106 | --outFilterMatchNmin 1 \ 107 | --outFilterMismatchNmax 2 \ 108 | --chimSegmentMin 15 \ 109 | --chimScoreMin 15 \ 110 | --chimScoreSeparation 10 \ 111 | --chimJunctionOverhangMin 15 \ 112 | 113 | 114 | * *This step may be skipped when single-end data is used.* Separate per-mate mapping. The naming of mate1 and mate2 has to be consistent with the order of the reads from the joint mapping performed above. In this case, SamplePairedRead_1.fastq.gz is the first mate since it was referenced at the first position in the joint mapping. 115 | 116 | .. code-block:: bash 117 | 118 | # Create a directory for mate1 119 | $ mkdir mate1 120 | $ cd mate1 121 | $ STAR --runThreadN 10 \ 122 | --genomeDir [genome] \ 123 | --outSAMtype None \ 124 | --readFilesIn Sample1_1.fastq.gz \ 125 | --readFilesCommand zcat \ 126 | --outFileNamePrefix [sample prefix] \ 127 | --outReadsUnmapped Fastx \ 128 | --outSJfilterOverhangMin 15 15 15 15 \ 129 | --alignSJoverhangMin 15 \ 130 | --alignSJDBoverhangMin 15 \ 131 | --seedSearchStartLmax 30 \ 132 | --outFilterMultimapNmax 20 \ 133 | --outFilterScoreMin 1 \ 134 | --outFilterMatchNmin 1 \ 135 | --outFilterMismatchNmax 2 \ 136 | --chimSegmentMin 15 \ 137 | --chimScoreMin 15 \ 138 | --chimScoreSeparation 10 \ 139 | --chimJunctionOverhangMin 15 \ 140 | 141 | * The process is repeated for the second mate: 142 | 143 | .. code-block:: bash 144 | 145 | # Create a directory for mate2 146 | $ mkdir mate2 147 | $ cd mate2 148 | $ STAR --runThreadN 10 \ 149 | --genomeDir [genome] \ 150 | --outSAMtype None \ 151 | --readFilesIn Sample1_2.fastq.gz \ 152 | --readFilesCommand zcat \ 153 | --outFileNamePrefix [sample prefix] \ 154 | --outReadsUnmapped Fastx \ 155 | --outSJfilterOverhangMin 15 15 15 15 \ 156 | --alignSJoverhangMin 15 \ 157 | --alignSJDBoverhangMin 15 \ 158 | --seedSearchStartLmax 30 \ 159 | --outFilterMultimapNmax 20 \ 160 | --outFilterScoreMin 1 \ 161 | --outFilterMatchNmin 1 \ 162 | --outFilterMismatchNmax 2 \ 163 | --chimSegmentMin 15 \ 164 | --chimScoreMin 15 \ 165 | --chimScoreSeparation 10 \ 166 | --chimJunctionOverhangMin 15 \ 167 | 168 | 169 | Detection of circular RNAs from ``chimeric.out.junction`` files with DCC 170 | =========================================================================== 171 | 172 | Acquiring suitable GTF files for repeat masking 173 | -------------------------------------------------------------------------------------- 174 | 175 | - It is strongly recommended to specify a repetitive region file in GTF format for filtering. 176 | 177 | - A suitable file can for example be obtained through the `UCSC table browser `_ . After choosing the genome, a group like **Repeats** or **Variation and Repeats** has to be selected. For the track, we recommend to choose **RepeatMasker** together with **Simple Repeats** and combine the results afterwards. 178 | 179 | - **Note**: the output file needs to comply with the GTF format specification. Additionally it may be the case that the names of chromosomes from different databases differ, e.g. **1** for chromosome 1 from ENSEMBL compared to **chr1** for chromosome 1 from UCSC. Since the chromosome names are important for the correct functionality of DCC a sample command for converting the identifiers may be: 180 | 181 | .. code-block:: bash 182 | 183 | # Example to convert UCSC identifiers to to ENSEMBL standard 184 | 185 | $ sed -i 's/^chr//g' your_repeat_file.gtf 186 | 187 | Preparation of files containing the paths to required ``chimeric.out.junction`` files 188 | -------------------------------------------------------------------------------------- 189 | 190 | * ``samplesheet`` file, containing the paths to the jointly mapped ``chimeric.out.junction`` files 191 | 192 | .. code-block:: bash 193 | 194 | $ cat samplesheet 195 | /path/to/STAR/sample_1/joint_mapping/chimeric.out.junction 196 | /path/to/STAR/sample_2/joint_mapping/chimeric.out.junction 197 | /path/to/STAR/sample_3/joint_mapping/chimeric.out.junction 198 | 199 | 200 | * ``mate1`` file, containing the paths to ``chimeric.out.junction`` files of the separately mapped first read of paired-end data 201 | 202 | .. code-block:: bash 203 | 204 | $ cat mate2 205 | /path/to/STAR/sample_1_mate1/joint_mapping/chimeric.out.junction 206 | /path/to/STAR/sample_2_mate1/joint_mapping/chimeric.out.junction 207 | /path/to/STAR/sample_3_mate1/joint_mapping/chimeric.out.junction 208 | 209 | 210 | * ``mate2`` file, containing the paths to ``chimeric.out.junction`` files of the separately mapped first read of paired-end data 211 | 212 | .. code-block:: bash 213 | 214 | $ cat mate2 215 | /path/to/STAR/sample_1_mate2/joint_mapping/chimeric.out.junction 216 | /path/to/STAR/sample_2_mate2/joint_mapping/chimeric.out.junction 217 | /path/to/STAR/sample_3_mate2/joint_mapping/chimeric.out.junction 218 | 219 | Pre-mapped ``chimeric.out.junction`` files from Westholm et al. data set are part of the DCC distribution 220 | 221 | .. code-block:: bash 222 | 223 | $ /DCC/data/samplesheet # jointly mapped chimeric.junction.out files 224 | $ /DCC/data/mate1 # mate1 independently mapped chimeric.junction.out files 225 | $ /DCC/data/mate1 # mate2 independently mapped chimeric.junction.out files 226 | 227 | 228 | Runnning DCC 229 | -------------------------------------------------------------------------------------- 230 | 231 | After performing all preparation steps DCC can now be started: 232 | 233 | .. code-block:: bash 234 | 235 | # Run DCC to detect circRNAs, using Westholm data as example 236 | 237 | $ DCC @samplesheet \ # @ is generally used to specify a file name 238 | -mt1 @mate1 \ # mate1 file containing the mate1 independently mapped chimeric.junction.out files 239 | -mt2 @mate2 \ # mate2 file containing the mate1 independently mapped chimeric.junction.out files 240 | -D \ # run in circular RNA detection mode 241 | -R [Repeats].gtf \ # regions in this GTF file are masked from circular RNA detection 242 | -an [Annotation].gtf \ # annotation is used to assign gene names to known transcripts 243 | -Pi \ # run in paired independent mode, i.e. use -mt1 and -mt2 244 | -F \ # filter the circular RNA candidate regions 245 | -M \ # filter out candidates from mitochondrial chromosomes 246 | -Nr 5 6 \ minimum count in one replicate [1] and number of replicates the candidate has to be detected in [2] 247 | -fg \ # candidates are not allowed to span more than one gene 248 | -G \ # also run host gene expression 249 | -A [Reference].fa \ # name of the fasta genome reference file; must be indexed, i.e. a .fai file must be present 250 | 251 | # For single end, non-stranded data: 252 | $ DCC @samplesheet -D -R [Repeats].gtf -an [Annotation].gtf -F -M -Nr 5 6 -fg -G -A [Reference].fa 253 | 254 | $ DCC @samplesheet -mt1 @mate1 -mt2 @mate2 -D -S -R [Repeats].gtf -an [Annotation].gtf -Pi -F -M -Nr 5 6 -fg 255 | 256 | # For details on the parameters please refer to the help page of DCC: 257 | $ DCC -h 258 | 259 | **Notes:** 260 | 261 | * By default, DCC assumes that the data is stranded. For non-stranded data the ``-N`` flag should be used. 262 | 263 | * Although not mandatory, we strongly recommend to the ``-F`` filtering step 264 | 265 | 266 | ****************************************** 267 | Output files generated by DCC 268 | ****************************************** 269 | 270 | The output of DCC consists of the following four files: CircRNACount, CircCoordinates, LinearCount and CircSkipJunctions. 271 | 272 | - **CircRNACount:** a table containing read counts for circRNAs detected. First three columns are chr, circRNA start, circRNA end. From fourth column on are the circRNA read counts, one sample per column, shown in the order given in your samplesheet. 273 | 274 | - **CircCoordinates:** circular RNA annotations in BED format. The columns are chr, start, end, genename, junctiontype (based on STAR; 0: non-canonical; 1: GT/AG, 2: CT/AC, 3: GC/AG, 4: CT/GC, 5: AT/AC, 6: GT/AT), strand, circRNA region (startregion-endregion), overall regions (the genomic features circRNA coordinates interval covers). 275 | 276 | - **LinearCount:** host gene expression count table, same setup with CircRNACount file. 277 | 278 | - **CircSkipJunctions:** circSkip junctions. The first three columns are the same as in LinearCount/CircRNACount, the following columns represent the circSkip junctions found for each sample. circSkip junctions are given as chr:start-end:count, e.g. chr1:1787-6949:10. It is possible that for one circRNA multiple circSkip junctions are found due to the fact the the circular RNA may arise from different isoforms. In this case, multiple circSkip junctions are delimited with semicolon. A 0 implies that no circSkip junctions have been found for this circRNA. 279 | 280 | ******************************************************************************************************************* 281 | Test for host-independently regulated circRNAs with `CircTest `_ 282 | ******************************************************************************************************************* 283 | 284 | Prerequisites: 285 | 286 | - The `CircTest `_ package must be installed 287 | 288 | 289 | Import of DCC output files into R: 290 | ================================== 291 | 292 | Using user-generated data 293 | --------------------------- 294 | 295 | .. code-block:: R 296 | 297 | library(CircTest) 298 | 299 | CircRNACount <- read.delim('CircRNACount',header=T) 300 | LinearCount <- read.delim('LinearCount',header=T) 301 | CircCoordinates <- read.delim('CircCoordinates',header=T) 302 | 303 | CircRNACount_filtered <- Circ.filter(circ = CircRNACount, 304 | linear = LinearCount, 305 | Nreplicates = 6, 306 | filter.sample = 6, 307 | filter.count = 5, 308 | percentage = 0.1 309 | ) 310 | 311 | CircCoordinates_filtered <- CircCoordinates[rownames(CircRNACount_filtered),] 312 | LinearCount_filtered <- LinearCount[rownames(CircRNACount_filtered),] 313 | 314 | Alternatively, the pre-processed Westholm et al. data from CircTest package may be used: 315 | ----------------------------------------------------------------------------------------- 316 | 317 | .. code-block:: R 318 | 319 | library(CircTest) 320 | 321 | data(Circ) 322 | CircRNACount_filtered <- Circ 323 | data(Coordinates) 324 | CircCoordinates_filtered <- Coordinates 325 | data(Linear) 326 | LinearCount_filtered <- Linear 327 | 328 | Test for host-independently regulated circRNAs 329 | ==================================================================== 330 | 331 | Execute the test 332 | ------------------------------------------------------------------- 333 | 334 | .. code-block:: R 335 | 336 | test = Circ.test(CircRNACount_filtered, 337 | LinearCount_filtered, 338 | CircCoordinates_filtered, 339 | group=c(rep(1,6),rep(2,6),rep(3,6)) 340 | ) 341 | 342 | # Significant result may be shown in a summary table 343 | View(test$summary_table) 344 | 345 | Visualisation of significantly, host-independently regulated circRNAs 346 | ----------------------------------------------------------------------- 347 | 348 | .. code-block:: R 349 | 350 | for (i in rownames(test$summary_table)) { 351 | Circ.ratioplot(CircRNACount_filtered, 352 | LinearCount_filtered, 353 | CircCoordinates_filtered, 354 | plotrow=i, 355 | groupindicator1=c(rep('1days',6),rep('4days',6),rep('20days',6)), 356 | lab_legend='Ages' 357 | ) 358 | } 359 | 360 | For further details on the usage of CircTest please refer to the corresponding GitHub project. 361 | 362 | ****************************************** 363 | Problems, issues, and errors 364 | ****************************************** 365 | 366 | * In case of any problems or feature requests please do not hesitate to open an issue on GitHub: `Create an issue `_ 367 | * Please make sure to run DCC with the ``-k`` flag when reporting an error to keep temporary files important for debugging purposes 368 | * Please also always paste or include the DCC log file 369 | -------------------------------------------------------------------------------- /DCC/Circ_nonCirc_Exon_Match.py: -------------------------------------------------------------------------------- 1 | # given circRNA coordinates file and exon annotation gtf file, print out the adjacent exon coordinates and exon_id 2 | 3 | import os 4 | import re 5 | 6 | import HTSeq 7 | 8 | from .IntervalTree import IntervalTree 9 | 10 | 11 | class CircNonCircExon(object): 12 | def __init__(self, tmp_dir): 13 | self.tmp_dir = tmp_dir 14 | 15 | def print_start_end_file(self, circcoordinates): 16 | # Print start.bed and end.bed 17 | # Get start and end corresponding relationship 18 | start2end = {} 19 | circ = open(circcoordinates, 'r') 20 | start_bed = open(self.tmp_dir + 'tmp_start.bed', 'w') 21 | end_bed = open(self.tmp_dir + 'tmp_end.bed', 'w') 22 | header = True 23 | for lin in circ: 24 | lin = lin.rstrip() 25 | if header: 26 | header = False 27 | else: 28 | lin_split = lin.split('\t') 29 | start_bed.write( 30 | lin_split[0] + '\t' + lin_split[1] + '\t' + lin_split[1] + '\t' + '.' + '\t' + '.' + '\t' + 31 | lin_split[5] + '\n') 32 | end_bed.write( 33 | lin_split[0] + '\t' + lin_split[2] + '\t' + lin_split[2] + '\t' + '.' + '\t' + '.' + '\t' + 34 | lin_split[5] + '\n') 35 | # Here is only for strand data, because here store GenomicInterval object to 36 | # guide the matching of circStartAdjacentExon with circEndAdjacentExon, 37 | # If the data is non-strand, the matching will suffer from uncertain strand 38 | start2end.setdefault( 39 | HTSeq.GenomicInterval(lin_split[0], int(lin_split[1]), int(lin_split[1]), str(lin_split[5])), []).append( 40 | HTSeq.GenomicInterval(lin_split[0], int(lin_split[2]), int(lin_split[2]), str(lin_split[5]))) 41 | circ.close() 42 | start_bed.close() 43 | end_bed.close() 44 | return start2end 45 | 46 | def select_exon(self, gtf_file): 47 | gtf = HTSeq.GFF_Reader(gtf_file, end_included=True) 48 | new_gtf = open(self.tmp_dir + 'tmp_' + os.path.basename(gtf_file) + '.exon.sorted', 'w') 49 | gtf_exon = [] 50 | for feature in gtf: 51 | # Select only exon line 52 | if feature.type == 'exon': 53 | gtf_exon.append(feature.get_gff_line().split('\t')) 54 | else: 55 | pass 56 | gtf_exon_sorted = sorted(gtf_exon, key=lambda x: (x[0], int(x[3]), int(x[4]))) 57 | gtf_exon_sorted = ['\t'.join(s) for s in gtf_exon_sorted] 58 | new_gtf.writelines(gtf_exon_sorted) 59 | new_gtf.close() 60 | 61 | def modifyExon_id(self, exon_gtf_file): 62 | rtrn = True 63 | # write custom_exon_id as transcript_id:exon_number 64 | gtf = HTSeq.GFF_Reader(exon_gtf_file, end_included=True) 65 | # gff = True 66 | new_gtf = open(self.tmp_dir + os.path.basename(exon_gtf_file) + '.modified', 'w') 67 | exon_number = {} 68 | for feature in gtf: 69 | # if gff: 70 | # try: 71 | # feature.attr['ID'] 72 | # except KeyError: 73 | # gff = False 74 | # else: 75 | # pass 76 | # First look for transcript_id 77 | try: 78 | if feature.attr['transcript_id'] in exon_number: 79 | # if feature.iv.strand == '+': 80 | exon_number[feature.attr['transcript_id']] = exon_number[feature.attr['transcript_id']] + 1 81 | # else: 82 | # exon_number[feature.attr['transcript_id']] = exon_number[feature.attr['transcript_id']] - 1 83 | else: 84 | # if feature.iv.strand == '+': 85 | exon_number[feature.attr['transcript_id']] = 1 86 | # else: 87 | # exon_number[feature.attr['transcript_id']] = -1 88 | # if gff: 89 | # custom_exon_id = ';custom_exon_id'+'='+feature.attr['transcript_id']+':'+str(exon_number[feature.attr['transcript_id']]) 90 | # else: 91 | custom_exon_id = '; custom_exon_id' + ' ' + feature.attr['transcript_id'] + ':' + str( 92 | exon_number[feature.attr['transcript_id']]) 93 | except KeyError: 94 | # Try assume gff format 95 | try: 96 | if feature.attr['Parent'] in exon_number: 97 | # if feature.iv.strand == '+': 98 | exon_number[feature.attr['Parent']] = exon_number[feature.attr['Parent']] + 1 99 | # else: 100 | # exon_number[feature.attr['Parent']] = exon_number[feature.attr['Parent']] - 1 101 | else: 102 | # if feature.iv.strand == '+': 103 | exon_number[feature.attr['Parent']] = 1 104 | # else: 105 | # exon_number[feature.attr['Parent']] = -1 106 | custom_exon_id = ';custom_exon_id' + '=' + feature.attr['Parent'] + ':' + str( 107 | exon_number[feature.attr['Parent']]) 108 | except (KeyError, TypeError): 109 | print ( 110 | 'DCC confused with the annotation, cannot determine CircSkip junctions. ' 111 | 'If gtf file provided, one or two of the features cannot find: transcript_id. ' 112 | 'If gff file provided, cannot determine Parent feature.') 113 | rtrn = False 114 | break 115 | new_gtf.write(feature.get_gff_line().strip('\n') + custom_exon_id + '\n') 116 | 117 | # Do not print non exon features 118 | #### MAKE sure only modify and interact with exons!!!!!!!! FIrst get only exons!!! 119 | #### for gff3 files, go for IDs!!!!!! # Solved 120 | new_gtf.close() 121 | return rtrn 122 | 123 | def readModifiedgtf(self, modifiedgtf): 124 | # store a dictionary which custom_exon_id are keys, exon_id are values. 125 | gtf = HTSeq.GFF_Reader(modifiedgtf, end_included=True) 126 | custom_exon_id2exon_id = {} 127 | for feature in gtf: 128 | custom_exon_id2exon_id[feature.attr['custom_exon_id']] = feature.attr['exon_id'] 129 | return custom_exon_id2exon_id 130 | 131 | def readuniqgtf(self, uniqgtf): 132 | # Requires exon_id are uniq in the file 133 | gtf = HTSeq.GFF_Reader(uniqgtf, end_included=True) 134 | exon_id2custom_exon_id = {} 135 | for feature in gtf: 136 | exon_id2custom_exon_id[feature.attr['exon_id']] = feature.attr['custom_exon_id'] 137 | return exon_id2custom_exon_id 138 | 139 | def intersectcirc(self, circ_file, modified_gtf_file, strand=True, isStartBED=True): 140 | # input the result file of print_start_end_file 141 | input_bed_file = open(circ_file).readlines() 142 | exon_gtf_file = HTSeq.GFF_Reader(modified_gtf_file, end_included=True) 143 | gtf_exon_sorted = IntervalTree() 144 | for feature in exon_gtf_file: 145 | row = feature.attr 146 | current_bed_interval = feature.iv 147 | gtf_exon_sorted.insert(current_bed_interval, annotation=row) 148 | 149 | circ_exon_set = {} 150 | for bed_line in input_bed_file: 151 | bed_field = bed_line.split('\t') 152 | custom_exon_list = [] 153 | 154 | # we add 1bp in order for intersect to work correctly 155 | # different case for start or end bed file 156 | if isStartBED: 157 | start = int(bed_field[1]) 158 | end = int(bed_field[1]) + 1 159 | else: 160 | start = int(bed_field[1]) - 1 161 | end = int(bed_field[1]) 162 | 163 | # in order for the intersect to work, we need at least 1bp frame size 164 | current_bed_interval = HTSeq.GenomicInterval(bed_field[0], 165 | start, 166 | end, 167 | bed_field[5].strip() 168 | ) 169 | 170 | # for later processing however, we again need the "0" bp frame window 171 | insert_bed_interval = HTSeq.GenomicInterval(bed_field[0], 172 | int(bed_field[1]), 173 | int(bed_field[2]), 174 | bed_field[5].strip() 175 | ) 176 | # extract all customs exons 177 | gtf_exon_sorted.intersect(current_bed_interval, 178 | lambda x: custom_exon_list.append(x.annotation['custom_exon_id']) 179 | ) 180 | 181 | if custom_exon_list: # if we found one or more custom exons 182 | for custom_exon in custom_exon_list: # go through the list 183 | circ_exon_set.setdefault(insert_bed_interval, set()).add(custom_exon) # and add them to the set 184 | 185 | # return the filled set 186 | return circ_exon_set 187 | 188 | def printuniq(self, Infile): 189 | f = open(Infile, 'r').readlines() 190 | keys = [] 191 | for lin in f: 192 | lin_split = lin.split('\t') 193 | keys.append(lin_split[0] + '\t' + lin_split[1] + '\t' + lin_split[2]) 194 | for lin in f: 195 | lin_split = lin.split('\t') 196 | if keys.count(lin_split[0] + '\t' + lin_split[1] + '\t' + lin_split[2]) == 1: 197 | print(lin.strip('\n')) 198 | 199 | def readgtf(self, gtf_file): 200 | # store nonCircExons based on transcript_id and exon_number with all its annotations from different transcripts 201 | gtf = HTSeq.GFF_Reader(gtf_file, end_included=True) 202 | nonCircExons = {} # A list of dictionaries 203 | for feature in gtf: 204 | nonCircExons.setdefault(feature.iv, []).append(feature.attr) 205 | return nonCircExons 206 | 207 | def getAdjacent(self, custom_exon_id, start=True, reverse=False): 208 | # Need to determine the oder. (Some exon ids increasing from first exon to last of the transcript, 209 | # irrelevant to strand. But some id increase with coordinates, in this case, for - strand, exon id will 210 | # ACTUALLY decrease from 5' to 3'. First determine whether exon id is reverse oder for - strand. 211 | # 212 | # Need a function to determine order. !!! 213 | # Solved by sort gtf and assign id to exon based on occuring order. Thus for - strand, order reverse. 214 | # 215 | if reverse: 216 | if start: 217 | exon_number = int(custom_exon_id.split(':')[1]) - 1 218 | else: 219 | exon_number = int(custom_exon_id.split(':')[1]) + 1 220 | else: 221 | if start: 222 | exon_number = int(custom_exon_id.split(':')[1]) - 1 223 | else: 224 | exon_number = int(custom_exon_id.split(':')[1]) + 1 225 | if exon_number == -1: 226 | return 'None' 227 | else: 228 | transcript_id = custom_exon_id.split(':')[0] 229 | return transcript_id + ':' + str(exon_number) 230 | 231 | def getgtforder(self, modified_gtf_file): 232 | gtf = HTSeq.GFF_Reader(modified_gtf_file, end_included=True) 233 | seen = {} 234 | for feature in gtf: 235 | if feature.type == 'exon' and feature.iv.strand == '-': 236 | try: 237 | parent = feature.attr['transcript_id'] 238 | seen[parent] = feature # GTF 239 | except KeyError: 240 | parent = feature.attr['Parent'] 241 | seen[parent] = feature # GFF3 242 | if parent in seen: 243 | # found one transcript with multiple exon, try determine order now 244 | if (seen[parent].iv.start - feature.iv.start) * ( 245 | self.getcustom_id_num(seen[parent].attr['custom_exon_id']) - self.getcustom_id_num( 246 | feature.attr['custom_exon_id'])) > 0: 247 | return True 248 | else: 249 | return False 250 | 251 | 252 | def getIDnum(self, ID): 253 | # Get the ID number of ID feature of GFF3 file 254 | res = re.findall(r'\d+', ID) 255 | if len(res) > 1: 256 | return None 257 | print('Cannot correctly determine ID.') 258 | else: 259 | return res[0] 260 | 261 | def getcustom_id_num(self, custom_id): 262 | return int(custom_id.split(':')[1]) 263 | 264 | def readHTSeqCount(self, HTSeqCount, exon_id2custom_exon_id): 265 | Count = open(HTSeqCount, 'r').readlines() 266 | Count_custom_exon_id = {} 267 | for lin in Count: 268 | lin_split = lin.split('\t') 269 | if lin_split[0] == '__no_feature': 270 | break 271 | else: 272 | Count_custom_exon_id[exon_id2custom_exon_id[lin_split[0]]] = int(lin_split[1]) 273 | return Count_custom_exon_id 274 | 275 | def findcircAdjacent(self, circExons, Custom_exon_id2Iv, Iv2Custom_exon_id, start=True): 276 | circAdjacentExons = {} 277 | circAdjacentExonsIv = {} 278 | for key in list(circExons.keys()): 279 | for ids in circExons[key]: 280 | try: 281 | interval = Custom_exon_id2Iv[self.getAdjacent(ids, start=start)] 282 | interval2ids = Iv2Custom_exon_id[interval] 283 | except KeyError: # CircExon is the start or end of that transcript 284 | interval = 'None' 285 | interval2ids = 'None' 286 | circAdjacentExons.setdefault(key, []).extend(interval2ids) 287 | circAdjacentExonsIv.setdefault(key, []).append(interval) 288 | # From custom_exon_id find out the interval, from interval find out all the custom_exon_ids for that interval 289 | return circAdjacentExons, circAdjacentExonsIv 290 | 291 | def printCounts(self, Exons, Count_custom_exon_id, Custom_exon_id2Length): 292 | # Print the counts of circexons and adjacentexons 293 | # Exons: dictionaries with intervals as key, custom_exon_id as values 294 | ExonCounts = {} 295 | for key in list(Exons.keys()): 296 | counts = [] 297 | for ids in Exons[key]: # If for circAdjacentExons, ids here is a list 298 | try: 299 | counts.append(ids + ' FPKM=' + str(float(Count_custom_exon_id[ids]) / Custom_exon_id2Length[ids])) 300 | except KeyError: 301 | pass 302 | ExonCounts[key] = counts 303 | return ExonCounts 304 | 305 | # For circExons, no problem because all the circExons are selected from deduplicates, but those one region has more 306 | # than one count (one region has more than one distinct exon) shoul left out, because the reads counting process is ambigous. 307 | 308 | def readNonUniqgtf(self, NonUniqgtf): 309 | gtf = HTSeq.GFF_Reader(NonUniqgtf, end_included=True) 310 | Iv2Custom_exon_id = {} 311 | Custom_exon_id2Iv = {} 312 | Custom_exon_id2Length = {} 313 | for feature in gtf: 314 | Iv2Custom_exon_id.setdefault(feature.iv, []).append(feature.attr['custom_exon_id']) 315 | Custom_exon_id2Iv.setdefault(feature.attr['custom_exon_id'], feature.iv) 316 | Custom_exon_id2Length.setdefault(feature.attr['custom_exon_id'], feature.iv.length) 317 | return (Iv2Custom_exon_id, Custom_exon_id2Iv, Custom_exon_id2Length) 318 | 319 | def printresults(self, circCount, circAdjacentCount, circExons, circAdjacentExons, prefix): 320 | result = open(prefix + 'exonFPKM', 'w') 321 | result_clean = open(prefix + 'exonFPKM_clean', 'w') 322 | for key in circCount: 323 | # This step discard those start/end mapped to more than one overlaping exons 324 | if len(circCount[key]) > 1 or len(circAdjacentCount[key]) > 1: 325 | pass 326 | else: 327 | result.write(str(key) + ': ' + '\t' + str(circCount[key]) + '\t' + str(circAdjacentCount[key]) + '\n') 328 | try: 329 | circ = str(circCount[key][0]).split('=')[1] 330 | except IndexError: 331 | circ = 'NA' 332 | try: 333 | circAdjacent = str(circAdjacentCount[key][0]).split('=')[1] 334 | except IndexError: 335 | circAdjacent = 'NA' 336 | 337 | result_clean.write(circ + '\t' + circAdjacent + '\n') 338 | result.close() 339 | result_clean.close() 340 | 341 | def exonskipjunction(self, circStartAdjacentExonsIv, circEndAdjacentExonsIv, start2end, strand=True): 342 | # A list of CircRNA interval to exon skip (circ skip) junctions 343 | junctions = {} 344 | for key in circStartAdjacentExonsIv: 345 | start = set() 346 | for itv0 in circStartAdjacentExonsIv[key]: 347 | try: 348 | start.add(str(itv0.end)) # Last base of left adjacent non-circEXON 349 | except AttributeError: 350 | pass 351 | 352 | # Find the end interval 353 | endiv = start2end.get(key, 354 | None) # A list, if more than one circ start from the same position, but have different ending. 355 | if endiv: 356 | for itv1 in endiv: 357 | end = set() 358 | # store the circ 359 | circ = HTSeq.GenomicInterval(itv1.chrom, key.start, itv1.end, key.strand) 360 | # but not every itv have adjacentexon 361 | try: 362 | for itv2 in circEndAdjacentExonsIv[itv1]: 363 | try: 364 | end.add(str(itv2.start)) # First base of right adjacent non-circEXON 365 | except AttributeError: 366 | pass 367 | except KeyError: 368 | pass 369 | 370 | if len(start) > 0 and len(end) > 0: 371 | for i in start: 372 | for j in end: 373 | junctions.setdefault(circ, []).append(itv1.chrom + '\t' + 374 | str(int(i) + 1) + '\t' 375 | + j + "\t" + key.strand) 376 | return junctions 377 | 378 | def readSJ_out_tab(self, SJ_out_tab): 379 | # read SJ.out.tab, store coordinates and read counts into a dictionary 380 | junctionReadCount = {} 381 | try: 382 | sj = open(SJ_out_tab, 'r') 383 | for lin in sj: 384 | 385 | lin_split = lin.split('\t') 386 | 387 | if lin_split[3] == "1": 388 | strand = "+" 389 | elif lin_split[3] == "2": 390 | strand = "-" 391 | else: 392 | strand = "?" 393 | 394 | junctionReadCount[lin_split[0] + '\t' + 395 | lin_split[1] + '\t' + 396 | lin_split[2] + '\t' + 397 | strand] = lin_split[6] 398 | sj.close() 399 | except IOError: 400 | print('Do you have SJ.out.tab files in your sample folder? DCC cannot find it.') 401 | return junctionReadCount 402 | 403 | def getskipjunctionCount(self, exonskipjunctions, junctionReadCount): 404 | # A list of CircRNA interval to exon skip (circ skip) junction read counts 405 | skipJctCount = {} 406 | for key in exonskipjunctions: 407 | junctions = exonskipjunctions[key] 408 | count = [] 409 | for jct in junctions: 410 | try: 411 | count.append(jct.split('\t')[0] + ':' + 412 | jct.split('\t')[1] + '-' + 413 | jct.split('\t')[2] + 414 | jct.split('\t')[3] + ':' + 415 | junctionReadCount[jct]) 416 | except KeyError: 417 | pass 418 | if len(count) > 0: 419 | counts = ';'.join((count)) 420 | skipJctCount[key] = counts 421 | return skipJctCount 422 | 423 | def readcircCount(self, circRNACount): 424 | circCount = {} 425 | Countfile = open(circRNACount, 'r') 426 | for lin in Countfile: 427 | lin_split = lin.split('\t') 428 | itv = HTSeq.GenomicInterval(lin_split[0], int(lin_split[1]), int(lin_split[2]), lin_split[5]) 429 | circCount[itv] = lin_split[4] 430 | Countfile.close() 431 | return circCount 432 | 433 | def printCirc_Skip_Count(self, circCount, skipJctCount, prefix): 434 | Circ_Skip_Count = [] 435 | for key in skipJctCount: 436 | try: 437 | count = skipJctCount[key] 438 | Circ_Skip_Count.append([key.chrom, str(key.start), str(key.end), count, circCount[key], key.strand]) 439 | except KeyError: 440 | pass 441 | 442 | # sort 443 | Circ_Skip_Count = sorted(Circ_Skip_Count, key=lambda x: (x[0], int(x[1]), int(x[2]))) 444 | 445 | # print "Circ_Skip_Count:" + str(Circ_Skip_Count) 446 | Circ_Skip_Count_file = open(prefix + 'CircSkipJunction', 'w') 447 | 448 | for sublist in Circ_Skip_Count: 449 | # for list_item in sublist: 450 | Circ_Skip_Count_file.write("\t".join(sublist) + "\n") 451 | 452 | Circ_Skip_Count_file.close() 453 | 454 | return prefix + 'CircSkipJunction' 455 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | -------------------------------------------------------------------------------- /DCC/main.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python2 2 | # -*- coding: utf-8 -*- 3 | 4 | import argparse 5 | import functools 6 | import logging 7 | import multiprocessing 8 | import os 9 | import random 10 | import string 11 | import sys 12 | import time 13 | 14 | import pysam 15 | 16 | from . import CombineCounts as Cc 17 | from . import circAnnotate as Ca 18 | from . import circFilter as Ft 19 | from . import findcircRNA as Fc 20 | from . import genecount as Gc 21 | from .fix2chimera import Fix2Chimera 22 | 23 | 24 | def main(circtools_parser=None): 25 | version = "0.5.0" 26 | 27 | parser = argparse.ArgumentParser(prog="DCC", formatter_class=argparse.RawDescriptionHelpFormatter, 28 | fromfile_prefix_chars="@", 29 | description="Contact: tobias.jakobi@med.uni-heidelberg.de || s6juncheng@gmail.com") 30 | 31 | parser.add_argument("--version", action="version", version=version) 32 | parser.add_argument("Input", metavar="Input", nargs="+", 33 | help="Input of the Chimeric.out.junction file from STAR. Alternatively, a sample sheet " 34 | "specifying where your chimeric.out.junction files are, each sample per line, " 35 | "provide with @ prefix (e.g. @samplesheet)") 36 | parser.add_argument("-k", "--keep-temp", dest="temp", action="store_true", default=False, 37 | help="Temporary files will not be deleted [default: False]") 38 | parser.add_argument("-T", "--threads", dest="cpu_threads", type=int, default=2, 39 | help="Number of CPU threads used for computation [default: 2]") 40 | parser.add_argument("-O", "--output", dest="out_dir", default="./", 41 | help="DCC output directory [default: .]") 42 | parser.add_argument("-t", "--temp", dest="tmp_dir", default="_tmp_DCC/", 43 | help="DCC temporary directory [default: _tmp_DCC/]") 44 | 45 | group = parser.add_argument_group("Find circRNA Options", "Options to find circRNAs from STAR output") 46 | group.add_argument("-D", "--detect", action="store_true", dest="detect", default=False, 47 | help="Enable circRNA detection from Chimeric.out.junction files [default: False]") 48 | group.add_argument("-ss", action="store_true", dest="secondstrand", default=False, 49 | help="Must be enabled for stranded libraries, aka 'fr-secondstrand' [default: False]") 50 | group.add_argument("-N", "--nonstrand", action="store_false", dest="strand", default=True, 51 | help="The library is non-stranded [default stranded]") 52 | group.add_argument("-E", "--endTol", dest="endTol", type=int, default=5, choices=list(range(0, 10)), 53 | help="Maximum base pair tolerance of reads extending over junction sites [default: 5]") 54 | group.add_argument("-m", "--maximum", dest="max", type=int, default=1000000, 55 | help="The maximum length of candidate circRNAs (including introns) [default: 1000000]") 56 | group.add_argument("-n", "--minimum", dest="min", type=int, default=30, 57 | help="The minimum length of candidate circRNAs (including introns) [default 30]") 58 | group.add_argument("-an", "--annotation", dest="annotate", 59 | help="Gene annotation file in GTF/GFF3 format, to annotate " 60 | "circRNAs by their host gene name/identifier") 61 | 62 | group.add_argument("-Pi", "--PE-independent", action="store_true", dest="pairedendindependent", default=False, 63 | help="Has to be specified if the paired end mates have also been mapped separately." 64 | "If specified, -mt1 and -mt2 must also be provided [default: False]") 65 | group.add_argument("-mt1", "--mate1", dest="mate1", nargs="+", 66 | help="For paired end data, Chimeric.out.junction files from mate1 independent mapping result") 67 | group.add_argument("-mt2", "--mate2", dest="mate2", nargs="+", 68 | help="For paired end data, Chimeric.out.junction files from mate2 independent mapping result") 69 | parser.add_argument_group(group) 70 | 71 | group = parser.add_argument_group("Filtering Options", "Options to filter the circRNA candidates") 72 | group.add_argument("-F", "--filter", action="store_true", dest="filter", default=False, 73 | help="If specified, the program will perform a recommended filter step on the detection results") 74 | group.add_argument("-f", "--filter-only", dest="filteronly", nargs=2, 75 | help="If specified, the program will only filter based on two files provided: " 76 | "1) a coordinates file [BED6 format] and 2) a count file. E.g.: -f example.bed counts.txt") 77 | group.add_argument("-M", "--chrM", action="store_true", dest="chrM", default=False, 78 | help="If specified, circRNA candidates located on the mitochondrial chromosome will be removed") 79 | group.add_argument("-R", "--rep_file", dest="rep_file", 80 | help="Custom repetitive region file in GTF format to filter out " 81 | "circRNA candidates in repetitive regions") 82 | group.add_argument("-L", "--Ln", dest="length", type=int, default=50, 83 | help="Minimum length in base pairs to check for repetitive regions [default 50]") 84 | group.add_argument("-Nr", nargs=2, type=int, metavar=("countthreshold", "replicatethreshold"), default=[2, 5], 85 | help="countthreshold replicatethreshold [default: 2,5]") 86 | group.add_argument("-fg", "--filterbygene", action="store_true", dest="filterbygene", default=False, 87 | help="If specified, filter also by gene annotation (candidates are not allowed to span" 88 | " more than one gene) default: False") 89 | parser.add_argument_group(group) 90 | 91 | group = parser.add_argument_group("Host gene count Options", "Options to count host gene expression") 92 | group.add_argument("-G", "--gene", action="store_true", dest="gene", default=False, 93 | help="If specified, the program will count host gene expression given circRNA coordinates " 94 | "[default: False]") 95 | group.add_argument("-C", "--circ", dest="circ", 96 | help="User specified circRNA coordinates, any tab delimited file with first three " 97 | "columns as circRNA coordinates: chr\tstart\tend, which DCC will use to count " 98 | "host gene expression") 99 | group.add_argument("-B", "--bam", dest="bam", nargs="+", 100 | help="A file specifying the mapped BAM files from which host gene expression is computed; " 101 | "must have the same order as input chimeric junction files") 102 | group.add_argument("-A", "--refseq", dest="refseq", 103 | help="Reference sequence FASTA file") 104 | 105 | parser.add_argument_group(group) 106 | 107 | # called directly from circtools 108 | if circtools_parser: 109 | parser = circtools_parser 110 | 111 | options = parser.parse_args() 112 | 113 | timestr = time.strftime("%Y-%m-%d_%H%M") 114 | 115 | if not os.path.isdir(options.out_dir): 116 | try: 117 | os.makedirs(options.out_dir) 118 | except OSError: 119 | print("Could not create output folder %s" % options.out_dir) 120 | logging.info("Could not create output folder %s" % options.out_dir) 121 | 122 | exit(-1) 123 | else: 124 | print("Output folder %s already exists, reusing" % options.out_dir) 125 | 126 | # create temporary directory if not existing 127 | 128 | if not os.path.isdir(options.tmp_dir): 129 | try: 130 | os.makedirs(options.tmp_dir) 131 | except OSError: 132 | print("Could not create temporary folder %s" % options.tmp_dir) 133 | exit(-1) 134 | else: 135 | print("Temporary folder %s already exists, reusing" % options.tmp_dir) 136 | 137 | logging.basicConfig(filename=os.path.join(options.out_dir, "DCC-" + timestr + ".log"), 138 | filemode="w", level=logging.DEBUG, 139 | format="%(asctime)s %(message)s") 140 | 141 | logging.info("DCC %s started" % version) 142 | print("DCC %s started" % version) 143 | logging.info('DCC command line: ' + ' '.join(sys.argv)) 144 | 145 | # Get input file names 146 | 147 | options.Input = remove_empty_lines(options.Input) 148 | 149 | if (options.mate1 and not options.mate1) or (options.mate2 and not options.mate1) and options.pairedendindependent: 150 | print("Only one mate data file supplied; check if both, -mt1 and -mt2 are specified.") 151 | logging.info("Only one mate data file supplied; check if both, -mt1 and -mt2 are specified.") 152 | exit(-1) 153 | 154 | if options.mate1: 155 | options.mate1 = remove_empty_lines(options.mate1) 156 | 157 | if options.mate2: 158 | options.mate2 = remove_empty_lines(options.mate2) 159 | 160 | filenames = [os.path.basename(name) for name in options.Input] 161 | 162 | samplelist = "\t".join(filenames) 163 | 164 | # make sure the user supplied path variables have a trailing / 165 | options.tmp_dir = os.path.join(options.tmp_dir, "") 166 | options.out_dir = os.path.join(options.out_dir, "") 167 | 168 | # set output file names 169 | output_coordinates = options.out_dir + "CircCoordinates" 170 | output_circ_counts = options.out_dir + "CircRNACount" 171 | output_linear_counts = options.out_dir + "LinearCount" 172 | output_skips = options.out_dir + "CircSkipJunctions" 173 | 174 | circfiles = [] # A list for .circRNA file names 175 | 176 | # check whether the junction file names have duplicates 177 | same = False 178 | if len(set(filenames)) != len(options.Input): 179 | logging.info( 180 | "Input file names have duplicates, add number suffix in input order to output files for distinction") 181 | print ("Input file names have duplicates, add number suffix in input order to output files for distinction") 182 | same = True 183 | 184 | cpu_count = multiprocessing.cpu_count() 185 | 186 | if options.cpu_threads <= cpu_count: 187 | print("%s CPU cores available, using %s" % (cpu_count, options.cpu_threads)) 188 | else: 189 | print("Only %s CPU cores available while %s requested, falling back to %s" % \ 190 | (cpu_count, options.cpu_threads, cpu_count)) 191 | options.cpu_threads = cpu_count 192 | 193 | pool = multiprocessing.Pool(processes=options.cpu_threads) 194 | 195 | if options.annotate is not None: 196 | checkfile(options.annotate, True) 197 | if options.rep_file is not None: 198 | checkfile(options.rep_file, True) 199 | 200 | # Make instance 201 | cm = Cc.Combine(options.tmp_dir) 202 | circann = Ca.CircAnnotate(tmp_dir=options.tmp_dir, strand=options.strand) 203 | 204 | if (not options.mate1 or not options.mate1) and options.pairedendindependent: 205 | logging.info('-Pi (Paired independent mode) specified but -mt1, -mt2, or both are missing. ' 206 | 'Will not use mate information.') 207 | print('-Pi (Paired independent mode) specified but -mt1, -mt2, or both are missing. ' 208 | 'Will not use mate information.') 209 | 210 | options.pairedendindependent = False 211 | 212 | if checkjunctionfiles(options.Input, options.mate1, options.mate2, options.pairedendindependent): 213 | logging.info("circRNA detection skipped due to empty junction files") 214 | print("circRNA detection skipped due to empty junction files") 215 | 216 | options.detect = False 217 | 218 | if options.bam and options.mate1 and (len(options.bam) != len(options.mate1)): 219 | logging.info("BAM file list is shorter than mate list. Maybe you forgot the @ (@file.list)?") 220 | print("BAM file list is shorter than mate list. Maybe you forgot the @ (@file.list)?") 221 | exit(-1) 222 | 223 | if options.bam and len(options.bam) == 1: 224 | 225 | f = os.popen('file -bi '+str(options.bam[0]), 'r') 226 | 227 | if f.read().startswith('text'): 228 | logging.info("Did you maybe you forgot the @ (-B @bam_file) parameter for the BAM list file " 229 | "(you specified only one file, but it is ASCII not binary)") 230 | print("Did you maybe you forgot the @ (-B @bam_file) parameter for the BAM list file " 231 | "(you specified only one file, but it is ASCII not binary)") 232 | exit(-1) 233 | 234 | if options.detect: 235 | logging.info("Starting to detect circRNAs") 236 | if options.strand: 237 | logging.info("Stranded data mode") 238 | else: 239 | logging.info("Non-stranded data, the strand of circRNAs guessed from the strand of host genes") 240 | print("WARNING: non-stranded data, the strand of circRNAs guessed from the strand of host genes") 241 | 242 | # Start de novo circular RNA detection model 243 | # Create instances 244 | f = Fc.Findcirc(endTol=options.endTol, maxL=options.max, minL=options.min) 245 | sort = Fc.Sort() 246 | 247 | if options.pairedendindependent: 248 | print("Please make sure that the read pairs have been mapped both, combined and on a per mate basis") 249 | logging.info("Please make sure that the read pairs have been mapped both, combined and on a per mate basis") 250 | 251 | # Fix2chimera problem by STAR 252 | print ("Collecting chimera information from mates-separate mapping") 253 | logging.info("Collecting chimera information from mates-separate mapping") 254 | Input = fixall(options.Input, options.mate1, options.mate2, options.out_dir, options.tmp_dir) 255 | else: 256 | Input = options.Input 257 | 258 | if options.strand: 259 | 260 | if options.pairedendindependent: 261 | circfiles = pool.map( 262 | functools.partial(wrapfindcirc, tmp_dir=options.tmp_dir, endTol=options.endTol, maxL=options.max, 263 | minL=options.min, strand=True, pairdendindependent=True, same=same), Input) 264 | else: 265 | circfiles = pool.map( 266 | functools.partial(wrapfindcirc, tmp_dir=options.tmp_dir, endTol=options.endTol, maxL=options.max, 267 | minL=options.min, strand=True, pairdendindependent=False, same=same), Input) 268 | 269 | else: 270 | if options.pairedendindependent: 271 | circfiles = pool.map( 272 | functools.partial(wrapfindcirc, tmp_dir=options.tmp_dir, endTol=options.endTol, maxL=options.max, 273 | minL=options.min, strand=False, pairdendindependent=True, same=same), Input) 274 | else: 275 | circfiles = pool.map( 276 | functools.partial(wrapfindcirc, tmp_dir=options.tmp_dir, endTol=options.endTol, maxL=options.max, 277 | minL=options.min, strand=False, pairdendindependent=False, same=same), Input) 278 | 279 | # Combine the individual count files 280 | # Create a list of ".circRNA" file names 281 | print("Combining individual circRNA read counts") 282 | logging.info("Combining individual circRNA read counts") 283 | 284 | cm.comb_coor(circfiles, strand=options.strand) 285 | cm.map(options.tmp_dir + "tmp_coordinates", circfiles, strand=options.strand) 286 | 287 | res = cm.combine([files + "mapped" for files in circfiles], col=7, circ=True) 288 | 289 | # swap strand if the sequences are sense strand 290 | if (options.secondstrand and options.strand): 291 | logging.info("Swapping strand information") 292 | strand_swap = {} 293 | strand_swap["+\n"] = "-\n" 294 | strand_swap["-\n"] = "+\n" 295 | toswap = open(options.tmp_dir + "tmp_coordinates").readlines() 296 | swaped = open(options.tmp_dir + "tmp_coordinatesswaped", "w") 297 | for lin in toswap: 298 | lin_split = lin.split("\t") 299 | lin_split[5] = strand_swap[lin_split[5]] 300 | swaped.write("\t".join(lin_split)) 301 | swaped.close() 302 | os.remove(options.tmp_dir + "tmp_coordinates") 303 | os.rename(options.tmp_dir + "tmp_coordinatesswaped", options.tmp_dir + "tmp_coordinates") 304 | 305 | if options.filter: 306 | cm.writeouput(options.tmp_dir + "tmp_circCount", res) 307 | if options.annotate: 308 | logging.info("Write in annotation") 309 | logging.info("Select gene features in Annotation file") 310 | annotation_tree = circann.selectGeneGtf(options.annotate) 311 | circann.annotate(options.tmp_dir + "tmp_coordinates", annotation_tree, 312 | options.tmp_dir + "tmp_coordinates_annotated") 313 | os.remove(options.tmp_dir + "tmp_coordinates") 314 | os.rename(options.tmp_dir + "tmp_coordinates_annotated", options.tmp_dir + "tmp_coordinates") 315 | else: 316 | cm.writeouput(output_circ_counts, res, samplelist, header=True) 317 | if options.annotate: 318 | logging.info("Write in annotation") 319 | logging.info("Select gene features in Annotation file") 320 | annotation_tree = circann.selectGeneGtf(options.annotate) 321 | circann.annotate(options.tmp_dir + "tmp_coordinates", annotation_tree, 322 | options.tmp_dir + "tmp_coordinates_annotated") 323 | circann.annotateregions(options.tmp_dir + "tmp_coordinates_annotated", annotation_tree, 324 | output_coordinates) 325 | else: 326 | 327 | os.rename(options.tmp_dir + "tmp_coordinates", output_coordinates) 328 | 329 | # Filtering 330 | if options.filter: 331 | logging.info("Filtering started") 332 | 333 | filt = Ft.Circfilter(length=options.length, 334 | countthreshold=options.Nr[0], 335 | replicatethreshold=options.Nr[1], 336 | tmp_dir=options.tmp_dir) 337 | 338 | if not options.detect and not options.gene and options.filteronly: 339 | try: 340 | file2filter = options.filteronly[0] 341 | coorfile = options.filteronly[1] 342 | logging.info("Using files %s and %s for filtering" % (options.filteronly[0], options.filteronly[1])) 343 | print("Using files %s and %s for filtering" % (options.filteronly[0], options.filteronly[1])) 344 | 345 | except IndexError: 346 | logging.error("Program exit because input error. Please check the input. If only use the program " 347 | "for filtering, a coordinate file in bed6 format and a count file is needed") 348 | 349 | sys.exit("Please check the input. If only use the program for filtering, a coordinate file in " 350 | "bed6 format and a count file is needed") 351 | 352 | elif not options.detect: 353 | 354 | sys.exit("Filter mode for detected circRNAs enabled without detection module.\nCombine with -f or -D.") 355 | 356 | elif options.detect: 357 | 358 | file2filter = options.tmp_dir + "tmp_circCount" 359 | coorfile = options.tmp_dir + "tmp_coordinates" 360 | logging.info("Using files _tmp_DCC/tmp_circCount and _tmp_DCC/tmp_coordinates for filtering") 361 | print("Using files _tmp_DCC/tmp_circCount and _tmp_DCC/tmp_coordinates for filtering") 362 | 363 | if options.rep_file: 364 | rep_file = options.rep_file 365 | else: 366 | # from pkg_resources import resource_filename 367 | # rep_file = resource_filename("DCC", "data/DCC.Repeats") 368 | rep_file = None 369 | count, indx = filt.readcirc(file2filter, coorfile) 370 | logging.info("Filtering by read counts") 371 | count0, indx0 = filt.filtercount(count, indx) # result of first filtering by read counts 372 | 373 | # filt.makeregion(indx0) 374 | # nonrep_left,nonrep_right = filt.nonrep_filter("_tmp_DCC/tmp_left","_tmp_DCC/tmp_right",rep_file) 375 | # filt.intersectLeftandRightRegions(nonrep_left,nonrep_right,indx0,count0) 376 | 377 | if rep_file is not None: 378 | logging.info("Filter by non repetitive region") 379 | filt.filter_nonrep(rep_file, indx0, count0) 380 | else: 381 | filt.dummy_filter(indx0, count0) 382 | 383 | if not options.chrM and not options.filterbygene: 384 | filt.sortOutput(options.tmp_dir + "tmp_unsortedWithChrM", output_circ_counts, 385 | output_coordinates, samplelist) 386 | 387 | # Filter chrM, if no further filtering, return "CircRNACount" and "CircCoordinates", 388 | # else return "_tmp_DCC/tmp_unsortedNoChrM" 389 | if options.chrM: 390 | logging.info("Deleting circRNA candidates from mitochondrial chromosome") 391 | filt.removeChrM(options.tmp_dir + "tmp_unsortedWithChrM") 392 | if not options.filterbygene: 393 | filt.sortOutput(options.tmp_dir + "tmp_unsortedNoChrM", output_circ_counts, 394 | output_coordinates, samplelist) 395 | else: 396 | os.rename(options.tmp_dir + "tmp_unsortedWithChrM", 397 | options.tmp_dir + "tmp_unsortedNoChrM") 398 | # Note in this case "_tmp_DCC/tmp_unsortedNoChrM" actually has chrM 399 | 400 | # Filter by gene annotation, require one circRNA could not from more than one gene. 401 | # return final "CircRNACount" and "CircCoordinates" 402 | if options.filterbygene: 403 | if options.annotate: 404 | logging.info("Filtering by gene annotation. " 405 | "CircRNA candidates from more than one genes are deleted") 406 | circann.filtbygene(options.tmp_dir + "tmp_unsortedNoChrM", 407 | options.tmp_dir + "tmp_unsortedfilterbygene") 408 | filt.sortOutput(options.tmp_dir + "tmp_unsortedfilterbygene", output_circ_counts, 409 | output_coordinates, samplelist) 410 | else: 411 | logging.warning( 412 | "To filter by gene annotation, a annotation file in GTF/GFF format needed, " 413 | "skiped filter by gene annotation") 414 | filt.sortOutput(options.tmp_dir + "tmp_unsortedNoChrM", output_circ_counts, 415 | output_coordinates, samplelist) 416 | 417 | # Add annotation of regions 418 | if options.annotate: 419 | circann.annotateregions(output_coordinates, annotation_tree, 420 | output_coordinates) 421 | 422 | logging.info("Filtering finished") 423 | 424 | if options.gene: 425 | # import the list of bamfile names as a file 426 | if not options.bam: 427 | print("No BAM files provided (-B) trying to automatically guess BAM file names") 428 | logging.info("No BAM files provided (-B) trying to automatically guess BAM file names") 429 | bamfiles = convertjunctionfile2bamfile(options.Input) 430 | if not bamfiles: 431 | print("Could not guess BAM file names, please provides them manually via -B") 432 | logging.info("Could not guess BAM file names, please provides them manually via -B") 433 | else: 434 | bamfiles = remove_empty_lines(options.bam) 435 | 436 | if not options.refseq: 437 | print("Please provide reference sequence, program will not count host gene expression") 438 | logging.warning("Please provide reference sequence, program will not count host gene expression") 439 | 440 | if options.refseq: 441 | linearfiles = [] # A list for .linear file names 442 | unsortedBAMS = checkBAMsorting(bamfiles) 443 | 444 | # check whether the number of bamfiles is equale to the number of chimeric.junction.out files 445 | if len(bamfiles) != len(options.Input): 446 | logging.error("The number of bam files does not match with chimeric junction files") 447 | sys.exit("The number of bam files does not match with chimeric junction files") 448 | 449 | elif len(unsortedBAMS) > 0: 450 | logging.error("The following BAM files seem to be not sorted by coordinate or are missing an index:") 451 | logging.error(', '.join(unsortedBAMS)) 452 | print("The following BAM files seem to be not sorted by coordinate or are missing an index:") 453 | print((', '.join(unsortedBAMS))) 454 | sys.exit("Error: not all BAM files are sorted by coordinate or are missing indices") 455 | else: 456 | # For each sample (each bamfile), do one host gene count, and then combine to a single table 457 | 458 | if options.circ: 459 | linearfiles = pool.map( 460 | functools.partial(wraphostgenecount, tmp_dir=options.tmp_dir, circ_coor=options.circ, 461 | ref=options.refseq, 462 | countlinearsplicedreads=False), bamfiles) 463 | else: 464 | if options.detect: 465 | linearfiles = pool.map( 466 | functools.partial(wraphostgenecount, tmp_dir=options.tmp_dir, circ_coor=output_circ_counts, 467 | ref=options.refseq, 468 | countlinearsplicedreads=False), bamfiles) 469 | else: 470 | logging.error("Linear gene counting only works if circRNA detection is enabled via -D.") 471 | print("Linear gene counting only works if circRNA detection is enabled via -D.") 472 | sys.exit("Please restart DCC with the -D flag.") 473 | 474 | logging.info("Finished linear gene expression counting, start to combine individual sample counts") 475 | 476 | # Combine all to a individual sample host gene count to a single table 477 | res = cm.combine(linearfiles, col=6, circ=False) 478 | cm.writeouput_linear(output_linear_counts, res, samplelist, header=True) 479 | logging.info("Finished combine individual linear gene expression counts") 480 | 481 | if not options.temp: 482 | deleted = cm.deletefile("", linearfiles) 483 | logdeleted(deleted) 484 | 485 | # CircSkip junction 486 | if options.annotate and options.detect and not options.circ: 487 | logging.info("Count CircSkip junctions") 488 | print("Count CircSkip junctions") 489 | SJ_out_tab = getSJ_out_tab(options.Input) 490 | CircSkipfiles = findCircSkipJunction(output_coordinates, options.tmp_dir, 491 | options.annotate, circfiles, SJ_out_tab, 492 | strand=options.strand, same=same) 493 | fin = open(output_coordinates, "r").readlines()[1:] 494 | with open(options.tmp_dir + "tmp_CircCoordinatesNoheader", "w") as fout: 495 | fout.writelines(fin) 496 | cm.map(options.tmp_dir + "tmp_CircCoordinatesNoheader", CircSkipfiles, strand=options.strand, col=4) 497 | CircSkipfilesmapped = [fname + "mapped" for fname in CircSkipfiles] 498 | res = cm.combine(CircSkipfilesmapped, col=9) 499 | cm.writeouput(output_skips, res, samplelist, header=True) 500 | else: 501 | logging.info("CircSkip junctions not counted, not running in detected mode (-D)") 502 | 503 | # Delete temporary files 504 | if not options.temp: 505 | deletion_regex = r"^tmp_\.*" 506 | deleted = cm.deletefile(options.tmp_dir, deletion_regex) 507 | logdeleted(deleted) 508 | try: 509 | os.rmdir(options.tmp_dir) 510 | except OSError: 511 | print("Could not delete temporary folder %s: not empty" % options.tmp_dir) 512 | logging.info("Could not delete temporary folder %s: not empty" % options.tmp_dir) 513 | 514 | try: 515 | os.rmdir(options.out_dir) 516 | except OSError: 517 | print("Not deleting output folder %s: contains files" % options.out_dir) 518 | logging.info("Not deleting output folder %s: contains files" % options.out_dir) 519 | 520 | print("Temporary files deleted") 521 | 522 | logging.info("DCC completed successfully") 523 | 524 | 525 | def fixall(joinedfnames, mate1filenames, mate2filenames, out_dir, tmp_dir): 526 | # Fix all 2chimera in one read/read pair for all inputs 527 | # outputs as a list of fixed filenames, with .fixed end 528 | outputs = [] 529 | fx = Fix2Chimera(tmp_dir) 530 | # check mate1 and mate2 input 531 | if len(mate1filenames) == len(mate2filenames) == len(joinedfnames): 532 | for i in range(len(joinedfnames)): 533 | extension = "." + id_generator() 534 | fx.fixchimerics(mate1filenames[i], mate2filenames[i], joinedfnames[i], 535 | os.path.join(tmp_dir, os.path.basename("tmp_" + joinedfnames[i]) + extension)) 536 | outputs.append(os.path.join(tmp_dir, os.path.basename("tmp_" + joinedfnames[i]) + extension)) 537 | else: 538 | logging.error("The number of input mate1, mate2 and joined mapping files are different") 539 | sys.exit("The number of input mate1, mate2 and joined mapping files are different") 540 | 541 | return outputs 542 | 543 | 544 | def checkfile(filename, previousstate): 545 | # check for file existence 546 | if not os.path.isfile(filename): 547 | sys.exit("ERROR: Required file " + str(filename) + " is missing, exiting") 548 | # check for file content 549 | elif os.stat(filename).st_size == 0: 550 | print(("WARNING: File " + str(filename) + " is empty!")) 551 | return True 552 | return previousstate 553 | 554 | 555 | def remove_empty_lines(namelist): 556 | return_list = [] 557 | for name in namelist: 558 | # print os.path.basename(name) 559 | if name != "": 560 | return_list.append(name) 561 | return return_list 562 | 563 | def checkjunctionfiles(joinedfnames, mate1filenames, mate2filenames, pairedendindependent): 564 | # Check if the junctions files have actually any content 565 | # if no, skip circRNA detection (and return True) 566 | 567 | skipcirc = False 568 | 569 | mate1empty = False 570 | mate2empty = False 571 | joinedempty = False 572 | 573 | if pairedendindependent: 574 | 575 | # check input files 576 | if len(mate1filenames) == len(mate2filenames) == len(joinedfnames): 577 | 578 | for i in range(len(joinedfnames)): 579 | # check for mate 1 files 580 | mate1empty = checkfile(mate1filenames[i], mate1empty) 581 | 582 | # check for mate 2 files 583 | mate2empty = checkfile(mate2filenames[i], mate2empty) 584 | 585 | # check for combined files 586 | joinedempty = checkfile(joinedfnames[i], joinedempty) 587 | 588 | if mate1empty or mate2empty or joinedempty: 589 | skipcirc = True 590 | logging.warning('One of the input junctions files is empty.') 591 | print('One of the input junctions files is empty.') 592 | else: 593 | skipcirc = True 594 | 595 | logging.warning('Input file lists have different length (mate 1 %d, mate 2 %d, joined %d).' % ( 596 | len(mate1filenames), len(mate2filenames), len(joinedfnames))) 597 | 598 | print(('Input file lists have different length (mate 1 %d, mate 2 %d, joined %d).' % ( 599 | len(mate1filenames), len(mate2filenames), len(joinedfnames)))) 600 | 601 | if skipcirc: 602 | logging.warning('Junction files seem empty, skipping circRNA detection module.') 603 | print('Junction files seem empty, skipping circRNA detection module.') 604 | 605 | return skipcirc 606 | 607 | else: 608 | 609 | for i in range(len(joinedfnames)): 610 | # check for combined files 611 | joinedempty = checkfile(joinedfnames[i], joinedempty) 612 | 613 | if joinedempty: 614 | skipcirc = True 615 | 616 | if skipcirc: 617 | logging.warning('Junction files seem empty, skipping circRNA detection module.') 618 | print('Junction files seem empty, skipping circRNA detection module.') 619 | 620 | return skipcirc 621 | 622 | 623 | def logdeleted(deleted): 624 | for itm in deleted: 625 | logging.info("Deleted temporary file " + itm) 626 | 627 | 628 | def mergefiles(output, *fnames): 629 | import shutil 630 | destination = open(output, "wb") 631 | for fname in fnames: 632 | shutil.copyfileobj(open(fname, "rb"), destination) 633 | destination.close() 634 | 635 | 636 | def convertjunctionfile2bamfile(junctionfilelist): 637 | # only works for STAR-like names: Aligned.noS.bam 638 | def getbamfname(junctionfname): 639 | import re 640 | import os 641 | # Get the stored directory 642 | dirt = "/".join((junctionfname.split("/")[:-1])) + "/" 643 | p = r".*Aligned\..*bam" 644 | bamfname = "" 645 | for fname in os.listdir(dirt): 646 | if re.match(p, fname): 647 | bamfname = dirt + re.findall(p, fname)[0] 648 | if bamfname: 649 | return bamfname 650 | 651 | bamfnames = [] 652 | for fname in junctionfilelist: 653 | entry = getbamfname(fname) 654 | if entry: 655 | bamfnames.append(getbamfname(fname)) 656 | return bamfnames 657 | 658 | 659 | # CircSkip junctions 660 | def findCircSkipJunction(CircCoordinates, tmp_dir, gtffile, circfiles, SJ_out_tab, strand=True, same=False): 661 | from .Circ_nonCirc_Exon_Match import CircNonCircExon 662 | CircSkipfiles = [] 663 | CCEM = CircNonCircExon(tmp_dir) 664 | # Modify gtf file 665 | if not os.path.isfile(tmp_dir + "tmp_" + os.path.basename(gtffile) + ".exon.sorted"): 666 | CCEM.select_exon(gtffile) 667 | if CCEM.modifyExon_id(tmp_dir + "tmp_" + os.path.basename(gtffile) + ".exon.sorted"): 668 | # Start and end coordinates 669 | start2end = CCEM.print_start_end_file(CircCoordinates) 670 | Iv2Custom_exon_id, Custom_exon_id2Iv, Custom_exon_id2Length = CCEM.readNonUniqgtf( 671 | tmp_dir + "tmp_" + os.path.basename(gtffile) + ".exon.sorted.modified") 672 | if strand: 673 | circStartExons = CCEM.intersectcirc(tmp_dir + "tmp_start.bed", tmp_dir + "tmp_" + os.path.basename( 674 | gtffile) + ".exon.sorted.modified", isStartBED=True) # Circle start or end to corresponding exons 675 | else: 676 | circStartExons = CCEM.intersectcirc(tmp_dir + "tmp_start.bed", 677 | tmp_dir + "tmp_" + os.path.basename(gtffile) + ".exon.sorted.modified", 678 | strand=False, isStartBED=True) 679 | circStartAdjacentExons, circStartAdjacentExonsIv = CCEM.findcircAdjacent(circStartExons, Custom_exon_id2Iv, 680 | Iv2Custom_exon_id, start=True) 681 | if strand: 682 | circEndExons = CCEM.intersectcirc(tmp_dir + "tmp_end.bed", tmp_dir + "tmp_" + os.path.basename( 683 | gtffile) + ".exon.sorted.modified", isStartBED=False) # Circle start or end to corresponding exons 684 | else: 685 | circEndExons = CCEM.intersectcirc(tmp_dir + "tmp_end.bed", 686 | tmp_dir + "tmp_" + os.path.basename(gtffile) + ".exon.sorted.modified", 687 | strand=False, isStartBED=False) 688 | circEndAdjacentExons, circEndAdjacentExonsIv = CCEM.findcircAdjacent(circEndExons, Custom_exon_id2Iv, 689 | Iv2Custom_exon_id, start=False) 690 | exonskipjunctions = CCEM.exonskipjunction(circStartAdjacentExonsIv, circEndAdjacentExonsIv, start2end) 691 | for indx, fname in enumerate(SJ_out_tab): 692 | if same: 693 | path = tmp_dir + "tmp_" + os.path.basename(fname).replace("SJ.out.tab", str(indx)) 694 | else: 695 | path = tmp_dir + "tmp_" + os.path.basename(fname).replace("SJ.out.tab", "") 696 | junctionReadCount = CCEM.readSJ_out_tab(fname) 697 | 698 | if len(junctionReadCount) == 0: 699 | logging.error("Do you have SJ.out.tab files in your sample folder? DCC cannot find it") 700 | logging.info("Cannot fine SJ.out.tab files, please check the path. circSkip will not be output") 701 | break 702 | else: 703 | skipJctCount = CCEM.getskipjunctionCount(exonskipjunctions, junctionReadCount) 704 | circCount = CCEM.readcircCount(circfiles[indx]) 705 | CircSkipfile = CCEM.printCirc_Skip_Count(circCount, skipJctCount, path) 706 | CircSkipfiles.append(CircSkipfile) 707 | return CircSkipfiles 708 | 709 | 710 | def getSJ_out_tab(chimeralist): 711 | SJ_out_tab = [] 712 | for fname in chimeralist: 713 | SJ_out_tab.append(fname.replace("Chimeric.out.junction", "SJ.out.tab")) 714 | return SJ_out_tab 715 | 716 | 717 | def id_generator(size=6, chars=string.ascii_uppercase + string.digits): 718 | return "".join(random.choice(chars) for _ in range(size)) 719 | 720 | 721 | def checkBAMsorting(bamfiles): 722 | unsortedBAMs = [] 723 | 724 | for file in bamfiles: 725 | 726 | bamfile = pysam.AlignmentFile(file, "rb") 727 | 728 | try: 729 | bamfile.check_index() 730 | except ValueError: 731 | print("BAM file %s has no index (%s.bai is missing)" % (file, file)) 732 | logging.info("BAM file %s has no index (%s.bai is missing)" % (file, file)) 733 | unsortedBAMs.append(file) 734 | break 735 | 736 | # Checking fort sorted reads is disabled to to issue #38: 737 | # https://github.com/dieterich-lab/DCC/issues/38 738 | 739 | # readcount = 0 740 | # readstarts = [] 741 | # 742 | # # until_eof=False makes sure that we get the actual ordering in the file 743 | # for read in bamfile.fetch(until_eof=False): 744 | # 745 | # readcount += 1 746 | # readstarts.append(read.reference_start) 747 | # 748 | # # sample only the first 100 reads 749 | # if readcount > 100: 750 | # break 751 | # 752 | # # close the BAM file again 753 | # bamfile.close() 754 | # 755 | # # compare sorted with unsorted list 756 | # if sorted(readstarts) != readstarts: 757 | # # BAM file is not not sorted 758 | # unsortedBAMs.append(file) 759 | 760 | # we return a list of unsorted files 761 | # -> if empty everything is sorted 762 | # -> if not, we have a list of files to look at for the user 763 | return unsortedBAMs 764 | 765 | 766 | def wraphostgenecount(bamfile, tmp_dir, circ_coor, ref, countlinearsplicedreads=True): 767 | # create the Genecount object 768 | gc = Gc.Genecount(tmp_dir) 769 | 770 | # generate a unique thread ID 771 | tid = id_generator() 772 | 773 | # create an (temporary) output file based on tid and file name 774 | output = tmp_dir + "tmp_" + os.path.basename(bamfile) + "_" + tid + "_junction.linear" 775 | 776 | print("Counting host gene expression based on " \ 777 | "detected and filtered circRNA coordinates for %s" % bamfile) 778 | 779 | # launch the gene counting 780 | gc.comb_gen_count(circ_coor, bamfile, ref, output, countlinearsplicedreads) 781 | 782 | # return this input file's output name 783 | return output 784 | 785 | 786 | def wrapfindcirc(files, tmp_dir, endTol, maxL, minL, strand=True, pairdendindependent=True, same=False): 787 | # create local instance 788 | f = Fc.Findcirc(endTol=endTol, maxL=maxL, minL=minL) 789 | 790 | # Start de novo circular RNA detection model 791 | sort = Fc.Sort() 792 | indx = id_generator() 793 | logging.info("started circRNA detection from file %s" % files) 794 | print("started circRNA detection from file %s" % files) 795 | 796 | if same: 797 | circfilename = files + indx + ".circRNA" 798 | else: 799 | circfilename = files + ".circRNA" 800 | if pairdendindependent: 801 | f.printcircline(files, tmp_dir + "tmp_printcirclines." + indx) 802 | 803 | print("\t=> separating duplicates [%s]" % files) 804 | f.sepDuplicates(tmp_dir + "tmp_printcirclines." + indx, tmp_dir + "tmp_duplicates." + indx, 805 | tmp_dir + "tmp_nonduplicates." + indx) 806 | 807 | # Find small circles 808 | print("\t=> locating small circRNAs [%s]" % files) 809 | f.smallcirc(tmp_dir + "tmp_duplicates." + indx, tmp_dir + "tmp_smallcircs." + indx) 810 | 811 | if strand: 812 | # Find normal circles 813 | print("\t=> locating circRNAs (stranded mode) [%s]" % files) 814 | f.findcirc(tmp_dir + "tmp_nonduplicates." + indx, tmp_dir + "tmp_normalcircs." + indx, strand=True) 815 | else: 816 | print("\t=> locating circRNAs (unstranded mode) [%s]" % files) 817 | f.findcirc(tmp_dir + "tmp_nonduplicates." + indx, tmp_dir + "tmp_normalcircs." + indx, strand=False) 818 | 819 | # Merge small and normal circles 820 | print("\t=> merging circRNAs [%s]" % files) 821 | mergefiles(tmp_dir + "tmp_findcirc." + indx, tmp_dir + "tmp_smallcircs." + indx, 822 | tmp_dir + "tmp_normalcircs." + indx) 823 | else: 824 | if strand: 825 | print("\t=> locating circRNAs (stranded mode) [%s]" % files) 826 | f.findcirc(files, tmp_dir + "tmp_findcirc." + indx, strand=True) 827 | else: 828 | print("\t=> locating circRNAs (unstranded mode) [%s]" % files) 829 | f.findcirc(files, tmp_dir + "tmp_findcirc." + indx, strand=False) 830 | 831 | # Sort 832 | if strand: 833 | print("\t=> sorting circRNAs (stranded mode) [%s]" % files) 834 | sort.sort_count(tmp_dir + "tmp_findcirc." + indx, circfilename, strand=True) 835 | else: 836 | print("\t=> sorting circRNAs (unstranded mode) [%s]" % files) 837 | sort.sort_count(tmp_dir + "tmp_findcirc." + indx, circfilename, strand=False) 838 | 839 | logging.info("finished circRNA detection from file %s" % files) 840 | print("finished circRNA detection from file %s" % files) 841 | 842 | return circfilename 843 | 844 | 845 | if __name__ == "__main__": 846 | main() 847 | --------------------------------------------------------------------------------