Skip to content

Instantly share code, notes, and snippets.

@parashardhapola
Created August 10, 2016 12:27
Show Gist options
  • Save parashardhapola/0fe3d3e336d36798c72d49ef443c0767 to your computer and use it in GitHub Desktop.
Save parashardhapola/0fe3d3e336d36798c72d49ef443c0767 to your computer and use it in GitHub Desktop.
Class for searching G-quadruplex motifs. (Part of QuadBase2 webserver)
import re
from itertools import groupby
import os
"""
MIT License
Copyright (c) [2016] [Parashar Dhapola]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__author__ = "Parashar Dhapola"
__email__ = "parashar.dhapola@gmail.com"
class QuadMotifFinder():
"""
This class allows searching G-quadruplex motifs in given seuqences.
Please see the paper below for details and cite it if you use this code
QuadBase2: web server for multiplexed guanine quadruplex mining and
visualization
doi: 10.1093/nar/gkw425
"""
def __init__(self, fasta_file, savename, stem=3, loop_start=1,
loop_stop=7, greedy=True, bulge=0):
self.fastaFile = fasta_file
self.saveName = savename
self.stemSize = stem
self.minLoopSize = loop_start
self.maxLoopSize = loop_stop
self.greedySearch = greedy
self.bulgeSize = bulge
self.outHandles = {}
self._sanitize_params()
self.resOv, self.resNov = [], []
fastaGen = self._read_fasta(self.fastaFile)
for h, s in fastaGen:
for i in ['+', '-']:
signature, motifOv, motifNov = self._make_motif(i)
self.resOv.extend(self._run_regex(s, h, motifOv, signature))
self.resNov.extend(self._run_regex(s, h, motifNov, signature))
self.outHandles['ov'].write("\n".join(self.resOv) + "\n")
self.outHandles['nov'].write("\n".join(self.resNov) + "\n")
self.outHandles['ov'].close()
self.outHandles['nov'].close()
def _sanitize_params(self):
try:
self.stemSize = int(self.stemSize)
self.minLoopSize = int(self.minLoopSize)
self.maxLoopSize = int(self.maxLoopSize)
self.bulgeSize = int(self.bulgeSize)
except:
raise TypeError('Please provide only integer values for size paramaters')
try:
self.greedySearch = bool(self.greedySearch)
except:
raise TypeError('Please provide only boolean values for greedySearch')
if self.minLoopSize >= self.maxLoopSize:
raise ValueError('Minimum loop size has to be larger than maximum loop size')
if os.path.isfile(self.fastaFile) is False:
print "File 'fasta_file' not found!."
if self.bulgeSize > 0 and self.stemSize != 3:
print "Bulge search disabled as stem size not equal to 3"
self.bulgeSize = 0
try:
self.outHandles['ov'] = open('%s_ov.bed' % self.saveName, 'w')
self.outHandles['nov'] = open('%s_nov.bed' % self.saveName, 'w')
except IOError:
raise IOError('Unable to open output file')
def _read_fasta(self, fasta_name):
fh = open(fasta_name)
faiter = (f[1] for f in groupby(fh, lambda line: line[0] == ">"))
for head in faiter:
head = head.next()[1:].strip()
s = "".join(s.strip() for s in faiter.next())
yield head, s
def _make_base(self, strand):
if strand == "+":
base = 'G'
invert_base = 'C'
else:
base = 'C'
invert_base = 'G'
return base, invert_base
def _make_signature(self, base):
return "".join(map(str, [base, self.stemSize, 'L',
self.minLoopSize, '-', self.maxLoopSize]))
def _make_stem_motif(self, base, invert_base):
if self.bulgeSize > 0:
stem_motif = '(?:%s|%s[AT%sN]{1,%d}%s|%s[AT%sN]{1,%d}%s)' % (base * 3, base, invert_base,
self.bulgeSize, base * 2, base * 2, invert_base, self.bulgeSize, base)
else:
stem_motif = '%s' % (base * self.stemSize)
return stem_motif
def _make_loop_motif(self, base, invert_base):
if self.greedySearch is True:
loop_motif = "[ACTGN]{%d,%d}" % (self.minLoopSize, self.maxLoopSize)
else:
loop_motif = '[ATGCN](?:[ATN%s]|(?!%s{2})%s){%d,%d}' % (
invert_base, base, base, self.minLoopSize - 1, self.maxLoopSize - 1)
return loop_motif
def _make_motif(self, strand):
base, invert_base = self._make_base(strand)
quad_signature = self._make_signature(base)
stem_motif = self._make_stem_motif(base, invert_base)
loop_motif = self._make_loop_motif(base, invert_base)
quad_motif_nov = (stem_motif + loop_motif) * 3 + stem_motif
quad_motif_nov = "(" + quad_motif_nov + ")"
quad_motif_ov = "(?=(%s))" % quad_motif_nov
return quad_signature, quad_motif_ov, quad_motif_nov
def _run_regex(self, seq, name, pattern, signature):
regex = re.compile(pattern, flags=re.IGNORECASE)
reg_obj = regex.finditer(seq)
res = []
for match in reg_obj:
temp_res = [name, match.start(), match.start() + len(match.group(1)) + 1,
len(match.group(1)), signature, match.group(1)]
res.append("\t".join(map(str, temp_res)))
return res
if __name__ == "__main__":
with open('testquad.fa', 'w') as OUT:
OUT.write('>hell\nACTGCGGGTACGGGGATCGGGGGATCGTGGGGGGATCGGGGGG')
q = QuadMotifFinder('testquad.fa', 'quads', stem=3, loop_start=2, bulge=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment