/
run_infernal.py
executable file
·176 lines (132 loc) · 4.64 KB
/
run_infernal.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
175
176
#!/usr/local/bin/python
"""A thin wrapper around hmmer 2.x suite of tools ()"""
__version__ = '$Id$'
import os
import sys
import logging
import commands
import subprocess
import re
import sequtil
log = logging
def getparams(**args):
return args
# def get_slices(line, slices):
# return [line.__getslice__(*slice).strip() for slice in slices]
def parse_cmstats(input):
if len(input) < 50 and os.access(input, os.F_OK):
# assume input is a filename
iterover = open(input)
# assume input is a string
else:
iterover = input.splitlines()
data = []
headers = None
slices = None
for line in iterover:
if line.startswith('# seq idx'):
headers = line
elif line.startswith('# ---') and headers:
slices = [i.span() for i in re.finditer('-+',line)]
get_slices = lambda line: [line.__getslice__(*slice).strip() for slice in slices]
headers = ['_'.join(h.split()) for h in get_slices(headers)]
elif line.strip() and not line.startswith('#') and slices:
data.append( dict(zip(headers, get_slices(line))) )
return data
def cmbuild(infile, outfile=None, defaults=None, quiet=False, dryrun=False, **params):
infile = os.path.abspath(infile)
if outfile:
outfile = os.path.abspath(outfile)
elif outfile is None:
outfile = os.path.join(os.path.split(infile)[0], sequtil.randomname(length=10)+'.cm')
stdoutdata, stderrdata = _run('cmbuild',
F=None,
args=[outfile, infile],
quiet=quiet,
dryrun=dryrun,
**params)
return outfile
def cmalign(cmfile, fastafile, outfile=None, statsfile=None,
defaults=None, quiet=False, dryrun=False, **params):
"""
Align sequences in fastafile against profile defined in cmfile.
required arguments
------------------
* cmfile - alignment profile, eg, output of cmbuild
* fastafile - file containing sequences in fasta format
optional arguments
------------------
* outfile - name of output alignment (Stockholm format); uses
name of fasta file if None
* statsfile - optional filename for alignment statistics
* defaults, quiet, dryrun, params - see help(Seq.run_infernal._run)
output
------
returns a two-tuple: (outfile, align_data)
* outfile - name of output file containing the alignment
* align_data - output of Seq.run_infernal.parse_cmstats
"""
cmfile = os.path.abspath(cmfile)
fastafile = os.path.abspath(fastafile)
if outfile:
outfile = os.path.abspath(outfile)
elif outfile is None:
outfile = os.path.join(os.path.split(fastafile)[0], sequtil.randomname(length=10)+'.sto')
stdoutdata, stderrdata = _run('cmalign',
o=outfile,
args=[cmfile, fastafile],
quiet=quiet,
dryrun=dryrun,
**params)
if not stderrdata and not dryrun:
if not statsfile:
statsfile = os.path.splitext(outfile)[0]+'.cmalign'
open(statsfile,'w').write(stdoutdata)
align_data = parse_cmstats(stdoutdata)
else:
outfile, align_data = None, None
return outfile, align_data
def _run(runcmd, args=None, defaults=None, quiet=False, dryrun=False, **params):
"""
Returns the name of the outfile.
* cmd - name of the executable
* args - unmodified arguments appended to end of command line
* dryrun - build the command line and quit
* defaults - an optional dict of key=val parameters
* params - pass arguments as either key=val pairs, or as
key='' if key has no argument
"""
cmd = sequtil.find_exec(runcmd)
if cmd is None:
raise OSError('%s could not be found' % runcmd)
os_type = sequtil.get_os_type()
if os_type != 'POSIX':
raise OSError('Operating system must be POSIX-like')
if defaults is None:
defaults = {}
defaults.update(params)
arguments = [cmd]
for k,v in defaults.items():
if len(k) == 1:
dashes = '-'
else:
dashes = '--'
if v is None or not v.strip():
add = ['%(dashes)s%(k)s']
else:
add = ['%(dashes)s%(k)s', '%(v)s']
arguments.extend([fstr % locals() for fstr in add])
if args:
arguments.extend(args)
log.info(arguments)
log.info(' '.join(arguments))
if dryrun:
return None, None
else:
stdoutdata, stderrdata = subprocess.Popen(arguments, stdout=subprocess.PIPE).communicate()
if stderrdata:
log.error(stderrdata)
log.info(stdoutdata[:500])
if not quiet:
print stdoutdata
return stdoutdata, stderrdata