forked from andreas-wilm/compbio-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseqgrep.py
executable file
·175 lines (141 loc) · 5.16 KB
/
seqgrep.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
"""A grep for sequence files.
"""
#--- standard library imports
#
import os
import sys
import logging
# optparse deprecated from Python 2.7 on
from optparse import OptionParser
import re
import gzip
#--- third-party imports
#
from Bio import SeqIO
from Bio.Seq import Seq
#--- project specific imports
#
import bioutils
__author__ = "Andreas Wilm"
__version__ = "0.1"
__email__ = "andreas.wilm@gmail.com"
__license__ = "The MIT License (MIT)"
#global logger
# http://docs.python.org/library/logging.html
LOG = logging.getLogger("")
logging.basicConfig(level=logging.WARN,
format='%(levelname)s [%(asctime)s]: %(message)s')
def cmdline_parser():
"""
creates an OptionParser instance
"""
# http://docs.python.org/library/optparse.html
usage = "%prog: " + __doc__ + "\n" \
"usage: %prog [options] file[s]"
parser = OptionParser(usage=usage)
choices = ['seq', 'id']
parser.add_option("-s", "--search-in",
dest="search_in",
default="id", choices=choices,
help="Search in sequence or its name (%s)" % (choices))
parser.add_option("", "--verbose",
action="store_true",
dest="verbose",
help="be verbose")
parser.add_option("", "--debug",
action="store_true",
dest="debug",
help="debugging")
parser.add_option("", "--revcomp",
action="store_true",
dest="revcomp",
help="Reverse complement search string")
parser.add_option("-i", "--ignore-case",
action="store_true", dest="ignore_case",
help="Make search case sensitive")
parser.add_option("-v", "--invert-match",
action="store_true", dest="invert_match",
help="invert sense of matching")
return parser
def main():
"""
The main function
"""
parser = cmdline_parser()
(opts, args) = parser.parse_args()
if opts.verbose:
LOG.setLevel(logging.INFO)
if opts.debug:
LOG.setLevel(logging.DEBUG)
if len(args)<2:
parser.error("Need pattern and at least one seqfile as argument")
sys.exit(1)
# first arg is pattern. rest are files
pattern_arg = args[0]
if opts.revcomp:
pattern_arg = str(Seq(pattern_arg).reverse_complement())
LOG.info("Pattern after reverse complement: %s" % pattern_arg)
seqfiles_arg = args[1:]
LOG.debug("args=%s" % (args))
LOG.debug("pattern_arg=%s" % (pattern_arg))
LOG.debug("seqfiles_arg=%s" % (seqfiles_arg))
if opts.ignore_case:
regexp = re.compile(pattern_arg, flags=re.IGNORECASE)
else:
regexp = re.compile(pattern_arg)
for fseq in seqfiles_arg:
if fseq != "-" and not os.path.exists(fseq):
LOG.fatal("input file %s does not exist.\n" % fseq)
sys.exit(1)
print_file_prefix = False
if len(seqfiles_arg)>1:
print_file_prefix = True
for fseq in seqfiles_arg:
if fseq == "-":
fhandle = sys.stdin
else:
if fseq[-3:] == ".gz":
fhandle = gzip.open(fseq)
else:
fhandle = open(fseq, "rU")
fmt = bioutils.guess_seqformat(fseq)
if not fmt:
fmt = 'fasta'
LOG.info("Checking file %s (format %s)" % (fseq, fmt))
for record in SeqIO.parse(fhandle, fmt):
#LOG.debug("checking seq %s (len %d)" % (record.id, len(record.seq)))
if opts.search_in == 'seq':
target = record.seq
elif opts.search_in == 'id':
# special case fasta: id is everything before the
# first whitespace. description contains this as well.
if fmt == 'fasta':
target = record.description
else:
target = record.id
else:
raise ValueError, (
"internal error...not sure where to search in")
target = str(target)
match = regexp.search(target)
print_match = False
if match and not opts.invert_match:
LOG.debug("match.string=%s" % match.string)
print_match = True
elif opts.invert_match and not match:
print_match = True
if print_match:
#import pdb; pdb.set_trace()
prefix = ""
if print_file_prefix:
prefix = fseq + ":"
if fmt == 'fasta':
print "%s>%s\n%s%s" % (prefix, record.description, prefix, record.seq)
else:
print "%s>%s\n%s%s" % (prefix, record.id, prefix, record.seq)
if fhandle != sys.stdin:
fhandle.close()
if __name__ == "__main__":
main()
LOG.debug("FIXME: Add support coloured output, length filtering, support output format arg.")