-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhmmer_utils.py
183 lines (168 loc) · 6.78 KB
/
hmmer_utils.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
177
178
179
180
181
182
183
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 7 21:38:20 2017
@author: bryce
"""
#==============================================================================
# Copyright (C) 2017 Bryce L. Kille
# University of Illinois
# Department of Chemistry
#
# Copyright (C) 2017 Christopher J. Schwalen
# University of Illinois
# Department of Chemistry
#
# Copyright (C) 2017 Douglas A. Mitchell
# University of Illinois
# Department of Chemistry
#
# License: GNU Affero General Public License v3 or later
# Complete license availabel in the accompanying LICENSE.txt.
# or <http://www.gnu.org/licenses/>.
#
# This file is part of RODEO2.
#
# RODEO2 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RODEO2 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#==============================================================================
import os
import csv
import subprocess
import logging
import socket
from rodeo_main import VERBOSITY
WEB_TOOL = False
if socket.gethostname() == "rodeo.scs.illinois.edu":
WEB_TOOL = True
logger = logging.getLogger(__name__)
logger.setLevel(VERBOSITY)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(VERBOSITY)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
pid_prefix = None
def _generate_fasta_from_string(query_string):
handle = open(pid_prefix+"fasta_file.tmp.fasta", "w+")
handle.write(">temp_string\n" + query_string)
def _generate_hmmer(hmm_file):
hmmer_process = subprocess.call(["hmmscan", "-o", pid_prefix+"hmm_out.tmp.tab", "--cpu=1", "--noali",
"--domtblout", pid_prefix+"pFamInfo.tmp.tab", hmm_file,
pid_prefix+"fasta_file.tmp.fasta"])
#TODO try/except blocks for parsing to double check format
def _parse(n, e_cutoff):
ret_list = []
NUM_COLUMNS = 23
pfam_accession = ''
with open(pid_prefix+'pFamInfo.tmp.tab') as handle:
for line in csv.reader(handle, delimiter=' '):
if line[0][0] == '#':
continue
tmp_list = []
for item in line:
if item != '':
tmp_list.append(item)
if tmp_list[1] != pfam_accession: #Check to make sure its not the same as the last one
pfam_accession = tmp_list[1].split('.')[0]
# if pfam_accession == '-':
# pfam_accession = "N/A"
pfam_name = tmp_list[0]
description = ' '.join(tmp_list[NUM_COLUMNS-1:])
e_val = tmp_list[6]
if float(e_val) < e_cutoff and len(ret_list) < n: #Will go through one extra line but oh well #TODO
found = False
for i in range(len(ret_list)):
(pfam_accession2, description2, e_val2, name2) = ret_list[i]
if pfam_accession == pfam_accession2 and pfam_name == name2:
found = True
if float(e_val) < float(e_val2):
ret_list[i] = (pfam_accession, description2, float(e_val2), pfam_name)
break
if not found:
ret_list.append((pfam_accession, description, float(e_val), pfam_name))
else:
break
ret_list_final = []
for acc, desc, e_val, name in ret_list:
in_list = False
for final_acc, _, _, final_name in ret_list_final:
if acc == final_acc and name == final_name:
in_list = True
if not in_list:
ret_list_final.append((acc, desc, e_val, name))
return ret_list_final
def get_hmmer_info(query, primary_hmm, cust_hmm, n=5, e_cutoff=.001, query_is_accession=False): #TODO handle lists of accessions
"""Returns top n hmmscan hits with e_values lower than e_cutoff"""
try:
global pid_prefix
pid_prefix = "tmp_files/" + str(os.getpid())
_generate_fasta_from_string(query)
pfam_desc_list = []
try:
_generate_hmmer(primary_hmm)
pfam_desc_list = _parse(n, e_cutoff)
except OSError:
logger.error("Couldn't find %s" % (primary_hmm))
for hmm in cust_hmm:
if WEB_TOOL:
try:
for f in os.listdir(hmm):
if f[-4:].lower() != '.hmm' and f[-4:].lower() != '.lib':
continue
if f == 'Pfam-A.hmm':
continue
_generate_hmmer(hmm + f)
pfam_desc_list += _parse(n, e_cutoff)
except OSError:
logger.error("Couldn't find %s" % (hmm))
else:
try:
_generate_hmmer(hmm)
add_list = _parse(n, e_cutoff)
pfam_desc_list += add_list
except OSError:
logger.error("Couldn't find %s" % (hmm))
if len(pfam_desc_list) > 0:
pfam_desc_list = sorted(pfam_desc_list, key=lambda entry: entry[2])
pfam_desc_list = sorted(pfam_desc_list, key=lambda entry: entry[0])
pfam_temp_list = [pfam_desc_list[0]]
(curr_pfam, curr_desc, curr_eval, curr_name) = pfam_desc_list[0]
for i in range(len(pfam_desc_list)):
if pfam_desc_list[i][0] == pfam_temp_list[-1][0] and pfam_desc_list[i][3] == pfam_temp_list[-1][3]:
continue
pfam_temp_list.append(pfam_desc_list[i])
pfam_desc_list = sorted(pfam_temp_list, key=lambda entry: entry[2])
try:
os.remove(pid_prefix+'pFamInfo.tmp.tab')
os.remove(pid_prefix+"fasta_file.tmp.fasta")
os.remove(pid_prefix+"hmm_out.tmp.tab")
except:
pass
return pfam_desc_list
except KeyboardInterrupt:
try:
os.remove(pid_prefix+'pFamInfo.tmp.tab')
except:
pass
try:
os.remove(pid_prefix+"fasta_file.tmp.fasta")
except:
pass
try:
os.remove(pid_prefix+"hmm_out.tmp.tab")
except:
pass
logger.critical("SIGINT recieved during HMMScan")
raise KeyboardInterrupt