wwpdb.utils.seqdb-v2 0.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ """
2
+ File: NcbiBlastService.py
3
+ Author: Zukang Feng
4
+ Update: 24-May-2010
5
+ Version: 001 Initial version
6
+
7
+ """
8
+
9
+ __author__ = "Zukang Feng"
10
+ __email__ = "zfeng@rcsb.rutgers.edu"
11
+ __version__ = "V0.001"
12
+
13
+ import getopt
14
+ import logging
15
+ import re
16
+ import sys
17
+ import time
18
+
19
+ import requests
20
+
21
+ # To disable warning about not checking ssl certificates. Still needed?
22
+ import urllib3
23
+
24
+ urllib3.disable_warnings()
25
+
26
+ logger = logging.getLogger()
27
+
28
+
29
+ class NcbiBlastService:
30
+ """Utility class for running blastn service using nt database from NCBI site"""
31
+
32
+ def __init__(self, sequence):
33
+ self._sequence = sequence
34
+ self._baseUrl = "https://www.ncbi.nlm.nih.gov/blast/Blast.cgi"
35
+ self._result = None
36
+ self._checkInterval = 10
37
+
38
+ def RunService(self):
39
+ """Main function for running blastn service"""
40
+ params = {}
41
+ params["CMD"] = "Put"
42
+ params["DATABASE"] = "nt"
43
+ params["FILTER"] = "L"
44
+ params["QUERY"] = self._sequence
45
+ params["PROGRAM"] = "blastn"
46
+ # Submit the job
47
+ return_data = self._serviceSubmit(params)
48
+ jobid = self._GetJobId(return_data)
49
+ if jobid:
50
+ # print >> sys.stderr, jobid
51
+ time.sleep(10)
52
+ self._result = self._getResultfromServer(jobid)
53
+
54
+ def GetResult(self):
55
+ return self._result
56
+
57
+ def WriteResultFile(self, filename):
58
+ fh = open(filename, "w")
59
+ if self._result:
60
+ fh.write(self._result)
61
+ fh.close()
62
+
63
+ def _serviceSubmit(self, params):
64
+ """Submit job"""
65
+ # Get the data for the options
66
+ try:
67
+ reqH = requests.post(self._baseUrl, data=params, verify=False, timeout=30) # noqa: S501
68
+ reqH.raise_for_status()
69
+ return_data = reqH.text
70
+ return return_data
71
+ except Exception as exc:
72
+ logger.exception("Submission error=%s params=%s", str(exc), params)
73
+ return ""
74
+
75
+ @staticmethod
76
+ def _GetJobId(data):
77
+ """parse return html file and search for
78
+ <!--QBlastInfoBegin
79
+ RID = X8SRH0TH012
80
+ RTOE = 11
81
+ QBlastInfoEnd
82
+ -->
83
+ return job ID X8SRH0TH012
84
+ """
85
+
86
+ start = data.find("QBlastInfoBegin")
87
+ end = data.find("QBlastInfoEnd")
88
+
89
+ if start >= 0 and end > start + 15:
90
+ qlist = data[start + 15 : end].split("\n")
91
+ for e in qlist:
92
+ if e.find("RID") >= 0:
93
+ qlist1 = e.strip().split(" ")
94
+ if len(qlist1) == 3:
95
+ return qlist1[2]
96
+
97
+ return ""
98
+
99
+ def _getResultfromServer(self, jobId):
100
+ """Get result from server"""
101
+ self._clientPoll(jobId)
102
+
103
+ # status is READY, get the result xml file
104
+ params = {}
105
+ params["CMD"] = "Get"
106
+ params["RID"] = jobId
107
+ params["NCBI_GI"] = "yes"
108
+ params["FORMAT_TYPE"] = "XML"
109
+ return self._serviceSubmit(params)
110
+
111
+ def _clientPoll(self, jobId):
112
+ """Client-side poll"""
113
+ status = self._serviceGetStatus(jobId)
114
+ while status != "READY":
115
+ # print >> sys.stderr, status
116
+ time.sleep(self._checkInterval)
117
+ status = self._serviceGetStatus(jobId)
118
+
119
+ def _serviceGetStatus(self, jobId):
120
+ """Get job status"""
121
+ params = {}
122
+ params["CMD"] = "Get"
123
+ params["RID"] = jobId
124
+ # Submit the job
125
+ return_data = self._serviceSubmit(params)
126
+ return self._GetJobStatus(return_data)
127
+
128
+ @staticmethod
129
+ def _GetJobStatus(data):
130
+ """parse return html file and search for
131
+ QBlastInfoBegin
132
+ Status=READY
133
+ QBlastInfoEnd
134
+ return status READY
135
+ """
136
+
137
+ start = data.find("QBlastInfoBegin")
138
+ end = data.find("QBlastInfoEnd")
139
+
140
+ if start >= 0 and end > start + 15:
141
+ rlist = data[start + 15 : end].split("\n")
142
+ for e in rlist:
143
+ if e.find("Status") >= 0:
144
+ rlist1 = e.strip().split("=")
145
+ if len(rlist1) == 2:
146
+ return rlist1[1]
147
+
148
+ return ""
149
+
150
+
151
+ def main(argv): # pragma: no cover
152
+ opts, _args = getopt.getopt(argv, "s:o:", ["sequence=", "outfile="])
153
+ sequence = None
154
+ filename = None
155
+ for opt, arg in opts:
156
+ if opt in ("-s", "--sequence"):
157
+ fh = open(arg)
158
+ sequence = fh.read()
159
+ fh.close()
160
+ elif opt in ("-o", "--outfile"):
161
+ filename = arg + ".xml"
162
+
163
+ if sequence and filename:
164
+ sequence = re.sub("[\t \n]", "", sequence)
165
+ service = NcbiBlastService(sequence)
166
+ service.RunService()
167
+ service.WriteResultFile(filename)
168
+
169
+
170
+ if __name__ == "__main__": # pragma: no cover
171
+ try:
172
+ main(sys.argv[1:])
173
+ sys.exit(0)
174
+ except Exception as _exc: # noqa: BLE001
175
+ print(_exc) # noqa: T201
176
+ sys.exit(1)
@@ -0,0 +1,233 @@
1
+ """
2
+ File: ReadNcbiBlastXml.py
3
+ Author: Zukang Feng
4
+ Update: 24-May-2010
5
+ Version: 001 Initial version
6
+
7
+ """
8
+
9
+ __author__ = "Zukang Feng"
10
+ __email__ = "zfeng@rcsb.rutgers.edu"
11
+ __version__ = "V0.001"
12
+
13
+ import getopt
14
+ import sys
15
+ from xml.dom import minidom # noqa: S408
16
+
17
+ from wwpdb.utils.seqdb_v2.FetchNcbiXml import FetchNcbiXml
18
+
19
+
20
+ class ReadNcbiBlastXml:
21
+ """Read Uniprot blast result xml file and return the list of hits which contains:
22
+
23
+ dict['db_name']
24
+ dict['db_code']
25
+ dict['db_accession']
26
+ dict['identity']
27
+ dict['positive']
28
+ dict['gaps']
29
+ dict['midline']
30
+ dict['query']
31
+ dict['queryFrom']
32
+ dict['queryTo']
33
+ dict['subject']
34
+ dict['hitFrom']
35
+ dict['hitTo']
36
+ dict['alignLen']
37
+ dict['match_length']
38
+ dict['source_scientific']
39
+ dict['source_common']
40
+ dict['taxonomy_id']
41
+ """
42
+
43
+ def __init__(self, doc):
44
+ self._result = self._parse(doc)
45
+
46
+ def GetResult(self):
47
+ return self._result
48
+
49
+ def _parse(self, doc):
50
+ resultlist = []
51
+ hlist = doc.getElementsByTagName("Hit")
52
+ if not hlist:
53
+ return resultlist
54
+
55
+ length = None
56
+ for node in doc.getElementsByTagName("BlastOutput_query-len"):
57
+ if node.nodeType != node.ELEMENT_NODE:
58
+ continue
59
+
60
+ if node.tagName == "BlastOutput_query-len":
61
+ length = node.firstChild.data
62
+ break
63
+
64
+ for node in hlist:
65
+ if node.nodeType != node.ELEMENT_NODE:
66
+ continue
67
+
68
+ alignlist = self._ProcessHitTag(node.childNodes, length)
69
+ if alignlist:
70
+ for align in alignlist:
71
+ if length:
72
+ align["query_length"] = length
73
+ resultlist.append(align)
74
+
75
+ return resultlist
76
+
77
+ def _ProcessHitTag(self, nodelist, length):
78
+ resultlist = []
79
+ alignlist = []
80
+ description = ""
81
+ length = ""
82
+ gi = ""
83
+ code = ""
84
+ for node in nodelist:
85
+ if node.nodeType != node.ELEMENT_NODE:
86
+ continue
87
+
88
+ if node.tagName == "Hit_id":
89
+ gi = self._parseID(node.firstChild.data)
90
+ if not gi:
91
+ return resultlist
92
+ elif node.tagName == "Hit_accession":
93
+ code = node.firstChild.data
94
+ elif node.tagName == "Hit_def":
95
+ description = node.firstChild.data
96
+ elif node.tagName == "Hit_len":
97
+ length = node.firstChild.data
98
+ elif node.tagName == "Hit_hsps":
99
+ hlist = self._ProcessHit_hspsTag(node.childNodes, length)
100
+ if hlist:
101
+ for li in hlist:
102
+ alignlist.append(li) # noqa: S408,PERF402
103
+
104
+ if not gi or not alignlist:
105
+ return resultlist
106
+
107
+ # Get genbank sequence information
108
+ fetchobj = FetchNcbiXml(gi, "Nucleotide")
109
+ pdict = fetchobj.ParseNcbiXmlData()
110
+ if pdict and "taxonomy_id" in pdict:
111
+ fetchobj = FetchNcbiXml(pdict["taxonomy_id"], "taxonomy")
112
+ pdict = fetchobj.ParseNcbiXmlData()
113
+
114
+ for align in alignlist:
115
+ align["db_name"] = "GB"
116
+ align["db_code"] = code
117
+ align["db_accession"] = gi
118
+ align["db_description"] = description
119
+ align["db_length"] = length
120
+
121
+ # add genbank sequence information
122
+ if pdict:
123
+ for k, v in pdict.items():
124
+ if k not in align:
125
+ align[k] = v
126
+
127
+ resultlist.append(align)
128
+
129
+ return resultlist
130
+
131
+ @staticmethod
132
+ def _parseID(data):
133
+ # Parses NCBI fasta descriptor. Ignore PDB references
134
+ gi = ""
135
+ dlist = data.split("|")
136
+ if len(dlist) >= 2 and dlist[2] != "pdb":
137
+ gi = dlist[1]
138
+ return gi
139
+
140
+ def _ProcessHit_hspsTag(self, nodelist, length):
141
+ resultlist = []
142
+ for node in nodelist:
143
+ if node.nodeType != node.ELEMENT_NODE:
144
+ continue
145
+ if node.tagName != "Hsp":
146
+ continue
147
+
148
+ rdict = self._GetMatchAlignment(node.childNodes, length)
149
+ if rdict:
150
+ resultlist.append(rdict)
151
+ return resultlist
152
+
153
+ @staticmethod
154
+ def _GetMatchAlignment(nodelist, length):
155
+ rdict = {}
156
+ for node in nodelist:
157
+ if node.nodeType != node.ELEMENT_NODE:
158
+ continue
159
+
160
+ if node.tagName == "Hsp_identity":
161
+ rdict["identity"] = node.firstChild.data
162
+ elif node.tagName == "Hsp_positive":
163
+ rdict["positive"] = node.firstChild.data
164
+ elif node.tagName == "Hsp_gaps":
165
+ rdict["gaps"] = node.firstChild.data
166
+ elif node.tagName == "Hsp_midline":
167
+ rdict["midline"] = node.firstChild.data.replace("T", "U")
168
+ elif node.tagName == "Hsp_qseq":
169
+ rdict["query"] = node.firstChild.data.replace("T", "U")
170
+ elif node.tagName == "Hsp_query-from":
171
+ rdict["queryFrom"] = node.firstChild.data
172
+ elif node.tagName == "Hsp_query-to":
173
+ rdict["queryTo"] = node.firstChild.data
174
+ elif node.tagName == "Hsp_hseq":
175
+ rdict["subject"] = node.firstChild.data.replace("T", "U")
176
+ elif node.tagName == "Hsp_hit-from":
177
+ rdict["hitFrom"] = node.firstChild.data
178
+ elif node.tagName == "Hsp_hit-to":
179
+ rdict["hitTo"] = node.firstChild.data
180
+ elif node.tagName == "Hsp_align-len":
181
+ rdict["alignLen"] = node.firstChild.data
182
+ rdict["match_length"] = node.firstChild.data
183
+
184
+ if "identity" in rdict:
185
+ if length:
186
+ identity = int(rdict["identity"]) * 100 / int(length)
187
+ if identity < 70:
188
+ rdict.clear()
189
+ elif "alignLen" in rdict:
190
+ identity = int(rdict["identity"]) * 100 / int(rdict["alignLen"])
191
+ if identity < 70:
192
+ rdict.clear()
193
+
194
+ return rdict
195
+
196
+
197
+ class ReadNcbiBlastXmlFile(ReadNcbiBlastXml):
198
+ """"""
199
+
200
+ def __init__(self, fileName):
201
+ self._fileName = fileName
202
+ self._doc = minidom.parse(self._fileName) # noqa: S318
203
+ ReadNcbiBlastXml.__init__(self, self._doc)
204
+
205
+
206
+ class ReadNcbiBlastXmlString(ReadNcbiBlastXml):
207
+ """"""
208
+
209
+ def __init__(self, data):
210
+ self._data = data
211
+ self._doc = minidom.parseString(self._data) # noqa: S318
212
+ ReadNcbiBlastXml.__init__(self, self._doc)
213
+
214
+
215
+ def main(argv): # pragma: no cover
216
+ opts, _args = getopt.getopt(argv, "x:", ["xml="])
217
+ for opt, arg in opts:
218
+ if opt in ("-x", "--xml"):
219
+ obj = ReadNcbiBlastXmlFile(arg)
220
+ result = obj.GetResult()
221
+ for align in result:
222
+ for k, v in align.items():
223
+ print("%s=%s" % (k, v)) # noqa: T201
224
+ print("\n") # noqa: T201
225
+
226
+
227
+ if __name__ == "__main__": # pragma: no cover
228
+ try:
229
+ main(sys.argv[1:])
230
+ sys.exit(0)
231
+ except Exception as exc: # noqa: BLE001
232
+ print(exc) # noqa: T201
233
+ sys.exit(1)
@@ -0,0 +1,128 @@
1
+ ##
2
+ # File: ReadNcbiSummary.py
3
+ # Author: Zukang Feng
4
+ # Update: 24-May-2010
5
+ # Version: 001 Initial version
6
+ #
7
+ # Updates -
8
+ # 20-Apr-2013 jdw Capture title attribute in summary as key name
9
+ #
10
+ ##
11
+
12
+ __author__ = "Zukang Feng"
13
+ __email__ = "zfeng@rcsb.rutgers.edu"
14
+ __version__ = "V0.001"
15
+
16
+ import getopt
17
+ import sys
18
+ from xml.dom import minidom # noqa: S408
19
+
20
+
21
+ class ReadNcbiSummary:
22
+ """Parse eSummaryResult xml file from NCBI and put source organism and
23
+ taxonomy information into dictionary:
24
+ dict['source_scientific']
25
+ dict['source_common']
26
+ dict['taxonomy_id']
27
+ dict['name']
28
+ """
29
+
30
+ def __init__(self, doc):
31
+ self._dict = {}
32
+ if doc:
33
+ self._dict = self._parse(doc)
34
+
35
+ def GetResult(self):
36
+ return self._dict
37
+
38
+ @staticmethod
39
+ def _parse(doc):
40
+ """Parse the eSummaryResult xml file:
41
+
42
+ <eSummaryResult>
43
+ <DocSum>
44
+ <Id>300852</Id>
45
+ <Item Name="Title" Type="String">Thermus thermophilus HB8 xxxxxx xxxxxx </Item>
46
+ <Item Name="ScientificName" Type="String">Thermus thermophilus HB8</Item>
47
+ <Item Name="CommonName" Type="String"></Item>
48
+ <Item Name="TaxId" Type="Integer">300852</Item>
49
+ /DocSum>
50
+ </eSummaryResult>
51
+
52
+ and put values into dictionary:
53
+
54
+ dict['source_scientific']
55
+ dict['source_common']
56
+ dict['taxonomy_id']
57
+ dict['name']
58
+ """
59
+ rdict = {}
60
+
61
+ entryList = doc.getElementsByTagName("Item")
62
+ if entryList:
63
+ for node in entryList:
64
+ if node.nodeType != node.ELEMENT_NODE:
65
+ continue
66
+
67
+ name = node.attributes["Name"]
68
+ if not name:
69
+ continue
70
+ if name.value == "TaxId":
71
+ if node.firstChild and node.firstChild.data != "0":
72
+ rdict["taxonomy_id"] = node.firstChild.data
73
+ elif name.value == "ScientificName":
74
+ if node.firstChild:
75
+ rdict["source_scientific"] = node.firstChild.data
76
+ elif name.value == "CommonName":
77
+ if node.firstChild:
78
+ rdict["source_common"] = node.firstChild.data
79
+ elif name.value == "Title": # noqa: SIM102
80
+ if node.firstChild:
81
+ rdict["name"] = node.firstChild.data
82
+
83
+ return rdict
84
+
85
+
86
+ class ReadNcbiSummaryFile(ReadNcbiSummary):
87
+ """"""
88
+
89
+ def __init__(self, fileName):
90
+ self._fileName = fileName
91
+ self._doc = ""
92
+ try: # noqa: SIM105
93
+ self._doc = minidom.parse(self._fileName) # noqa: S318
94
+ except Exception as exc: # noqa: F841,BLE001 pylint: disable=unused-variable
95
+ pass
96
+ ReadNcbiSummary.__init__(self, self._doc)
97
+
98
+
99
+ class ReadNcbiSummaryString(ReadNcbiSummary):
100
+ """"""
101
+
102
+ def __init__(self, data):
103
+ self._data = data
104
+ self._doc = ""
105
+ try: # noqa: SIM105
106
+ self._doc = minidom.parseString(self._data) # noqa: S318
107
+ except Exception as exc: # noqa: F841,S318,BLE001 pylint: disable=unused-variable
108
+ pass
109
+ ReadNcbiSummary.__init__(self, self._doc)
110
+
111
+
112
+ def main(argv): # pragma: no cover
113
+ opts, _args = getopt.getopt(argv, "x:", ["xml="])
114
+ for opt, arg in opts:
115
+ if opt in ("-x", "--xml"):
116
+ obj = ReadNcbiSummaryFile(arg)
117
+ rdict = obj.GetResult()
118
+ for k, v in rdict.items():
119
+ print("%s=%s" % (k, v)) # noqa: T201
120
+
121
+
122
+ if __name__ == "__main__": # pragma: no cover
123
+ try:
124
+ main(sys.argv[1:])
125
+ sys.exit(0)
126
+ except Exception as _exc: # noqa: BLE001
127
+ print(_exc) # noqa: T201
128
+ sys.exit(1)