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,214 @@
1
+ """
2
+ File: ReadNcbiXml.py
3
+ Author: Zukang Feng
4
+ Update: 24-May-2010
5
+ Version: 001 Initial version
6
+
7
+ Updates --
8
+
9
+ 20-Apr-2013 jdw - provide options to avoid saving full sequence.
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 ReadNcbiXml:
22
+ """Parse GeneBank entry xml file and put seqeunce, source organism, and
23
+ taxonomy information into dictionary:
24
+ dict['sequence']
25
+ dict['source_scientific']
26
+ dict['taxonomy_id']
27
+ """
28
+
29
+ def __init__(self, doc):
30
+ self._dict = {}
31
+ self.__skipSequence = False
32
+ if doc:
33
+ self._dict = self._parse(doc)
34
+
35
+ def skipSequence(self):
36
+ self.__skipSequence = True
37
+
38
+ def GetResult(self):
39
+ return self._dict
40
+
41
+ def _parse(self, doc):
42
+ rdict = {}
43
+ db_code = None
44
+ entryList = doc.getElementsByTagName("GBSeq_accession-version")
45
+ if entryList:
46
+ for node in entryList:
47
+ if node.nodeType != node.ELEMENT_NODE:
48
+ continue
49
+ if node.tagName == "GBSeq_accession-version":
50
+ db_code = node.firstChild.data
51
+ break
52
+
53
+ # Get sequence:
54
+ sequence = None
55
+ if not self.__skipSequence:
56
+ entryList = doc.getElementsByTagName("GBSeq_sequence")
57
+ if entryList:
58
+ for node in entryList:
59
+ if node.nodeType != node.ELEMENT_NODE:
60
+ continue
61
+ if node.tagName == "GBSeq_sequence":
62
+ sequence = node.firstChild.data
63
+ break
64
+
65
+ if sequence:
66
+ sequence = self._ProcessRNASequence(sequence)
67
+
68
+ entryList = doc.getElementsByTagName("GBFeature")
69
+ if entryList:
70
+ for node in entryList:
71
+ if node.nodeType != node.ELEMENT_NODE:
72
+ continue
73
+
74
+ rdict = self._ProcessGBFeatureTag(node.childNodes)
75
+ if rdict:
76
+ break
77
+
78
+ if sequence:
79
+ rdict["sequence"] = sequence
80
+
81
+ if db_code:
82
+ rdict["db_code"] = db_code
83
+
84
+ return rdict
85
+
86
+ @staticmethod
87
+ def _ProcessRNASequence(sequence):
88
+ seq = sequence.upper()
89
+ seq = seq.replace("T", "U")
90
+ return seq
91
+
92
+ def _ProcessGBFeatureTag(self, nodeList):
93
+ """Get source information from
94
+ <GBFeature>
95
+ <GBFeature_key>source</GBFeature_key>
96
+ ......
97
+ <GBFeature_quals>
98
+ <GBQualifier>
99
+ <GBQualifier_name>organism</GBQualifier_name>
100
+ <GBQualifier_value>Thermus thermophilus HB8</GBQualifier_value>
101
+ </GBQualifier>
102
+ ......
103
+ <GBQualifier>
104
+ <GBQualifier_name>db_xref</GBQualifier_name>
105
+ <GBQualifier_value>taxon:300852</GBQualifier_value>
106
+ </GBQualifier>
107
+ ......
108
+ </GBFeature_quals>
109
+ </GBFeature>
110
+ """
111
+ rdict = {}
112
+ rtype = ""
113
+ for node in nodeList:
114
+ if node.nodeType != node.ELEMENT_NODE:
115
+ continue
116
+
117
+ if node.tagName == "GBFeature_key":
118
+ rtype = node.firstChild.data
119
+ if rtype != "source":
120
+ rdict.clear()
121
+ return rdict
122
+ elif node.tagName == "GBFeature_quals":
123
+ rdict = self._ProcessGBQualifierTag(node.childNodes)
124
+
125
+ if rtype != "source":
126
+ rdict.clear()
127
+
128
+ return rdict
129
+
130
+ @staticmethod
131
+ def _ProcessGBQualifierTag(nodeList):
132
+ """Get source_scientific from
133
+ <GBQualifier>
134
+ <GBQualifier_name>organism</GBQualifier_name>
135
+ <GBQualifier_value>Thermus thermophilus HB8</GBQualifier_value>
136
+ </GBQualifier>
137
+
138
+ and taxonomy_id from
139
+ <GBQualifier>
140
+ <GBQualifier_name>db_xref</GBQualifier_name>
141
+ <GBQualifier_value>taxon:300852</GBQualifier_value>
142
+ </GBQualifier>
143
+ """
144
+ rdict = {}
145
+ for node in nodeList:
146
+ if node.nodeType != node.ELEMENT_NODE:
147
+ continue
148
+
149
+ name = None
150
+ value = None
151
+ for childnode in node.childNodes:
152
+ if childnode.nodeType != node.ELEMENT_NODE:
153
+ continue
154
+
155
+ if childnode.tagName == "GBQualifier_name":
156
+ name = childnode.firstChild.data
157
+ elif childnode.tagName == "GBQualifier_value":
158
+ value = childnode.firstChild.data
159
+
160
+ if not name or not value:
161
+ continue
162
+
163
+ if name == "organism":
164
+ rdict["source_scientific"] = value
165
+ elif name == "db_xref" and value.find("taxon:") >= 0:
166
+ tlist = value.split(":")
167
+ rdict["taxonomy_id"] = tlist[1]
168
+
169
+ return rdict
170
+
171
+
172
+ class ReadNcbiXmlFile(ReadNcbiXml):
173
+ """"""
174
+
175
+ def __init__(self, fileName):
176
+ self._fileName = fileName
177
+ self._doc = ""
178
+ try: # noqa: SIM105
179
+ self._doc = minidom.parse(self._fileName) # noqa: S318
180
+ except Exception as exc: # noqa: F841,BLE001 pylint: disable=unused-variable
181
+ pass
182
+ ReadNcbiXml.__init__(self, self._doc)
183
+
184
+
185
+ class ReadNcbiXmlString(ReadNcbiXml):
186
+ """"""
187
+
188
+ def __init__(self, data):
189
+ self._data = data
190
+ self._doc = ""
191
+ try: # noqa: SIM105
192
+ self._doc = minidom.parseString(self._data) # noqa: S318
193
+ except Exception as exc: # noqa: F841,BLE001 pylint: disable=unused-variable
194
+ pass
195
+ ReadNcbiXml.__init__(self, self._doc)
196
+
197
+
198
+ def main(argv): # pragma: no cover
199
+ opts, _args = getopt.getopt(argv, "x:", ["xml="])
200
+ for opt, arg in opts:
201
+ if opt in ("-x", "--xml"):
202
+ obj = ReadNcbiXmlFile(arg)
203
+ rdict = obj.GetResult()
204
+ for k, v in rdict.items():
205
+ print("%s=%s" % (k, v)) # noqa: T201
206
+
207
+
208
+ if __name__ == "__main__": # pragma: no cover
209
+ try:
210
+ main(sys.argv[1:])
211
+ sys.exit(0)
212
+ except Exception as _exc: # noqa: BLE001
213
+ print(_exc) # noqa: T201
214
+ sys.exit(1)
@@ -0,0 +1,266 @@
1
+ ##
2
+ # File: ReadUnpBlastXml.py
3
+ # Author: Zukang Feng
4
+ # Update: 24-May-2010
5
+ # Version: 001 Initial version
6
+ #
7
+ # Updates:
8
+ #
9
+ # 03-Jan-2013 jdw adopt new FetchUnpXml class and fetch protocol.
10
+ # 05-Apr-2013 jdw add description and length details from the hit attributes
11
+ # 07-Apr-2013 jdw return isoform variant as a separate item.
12
+ # 19-Apr-2013 jdw restore db_code from the full uniprot entry.
13
+ ##
14
+
15
+ __author__ = "Zukang Feng"
16
+ __email__ = "zfeng@rcsb.rutgers.edu"
17
+ __version__ = "V0.001"
18
+
19
+ import getopt
20
+ import math
21
+ import sys
22
+ from xml.dom import minidom # noqa: S408
23
+
24
+ from wwpdb.utils.seqdb_v2.FetchUnpXml import FetchUnpXml
25
+
26
+
27
+ class ReadUnpBlastXml:
28
+ """Read Uniprot blast result xml file and return the list of hits which contains:
29
+
30
+ dict['db_name']
31
+ dict['db_code']
32
+ dict['db_accession']
33
+ dict['db_length']
34
+ dict['db_description']
35
+ dict['db_isoform']
36
+ dict['identity']
37
+ dict['positive']
38
+ dict['gaps']
39
+ dict['midline']
40
+ dict['query']
41
+ dict['queryFrom']
42
+ dict['queryTo']
43
+ dict['subject']
44
+ dict['hitFrom']
45
+ dict['hitTo']
46
+ dict['alignLen']
47
+ dict['match_length']
48
+ dict['sequence']
49
+ dict['ec']
50
+ dict['keyword']
51
+ dict['name']
52
+ dict['synonyms']
53
+ dict['gene']
54
+ dict['source_scientific']
55
+ dict['source_common']
56
+ dict['taxonomy_id']
57
+ dict['comments']
58
+ """
59
+
60
+ def __init__(self, doc, verbose=True, log=sys.stderr):
61
+ self.__verbose = verbose
62
+ self.__lfh = log
63
+ self._result = self._parse(doc)
64
+
65
+ def GetResult(self):
66
+ return self._result
67
+
68
+ def _parse(self, doc):
69
+ length = None
70
+ for node in doc.getElementsByTagName("sequence"):
71
+ if node.nodeType != node.ELEMENT_NODE:
72
+ continue
73
+
74
+ if node.tagName == "sequence" and node.attributes["length"]:
75
+ length = node.attributes["length"].value
76
+ break
77
+
78
+ mapping = {}
79
+ mapping["database"] = "db_name"
80
+ mapping["id"] = "db_code"
81
+ mapping["ac"] = "db_accession"
82
+ mapping["description"] = "db_description"
83
+ mapping["length"] = "db_length"
84
+ resultlist = []
85
+ entry = None
86
+ entryList = doc.getElementsByTagName("hits")
87
+ if len(entryList) > 0:
88
+ entry = entryList[0]
89
+ else:
90
+ return resultlist
91
+
92
+ total = entry.attributes["total"]
93
+ if total and total.value == "0":
94
+ return resultlist
95
+
96
+ fetchList = []
97
+ for node in entry.childNodes:
98
+ if node.nodeType != node.ELEMENT_NODE:
99
+ continue
100
+
101
+ if node.tagName != "hit":
102
+ continue
103
+
104
+ alignlist = self._ProcessAlignmentsTag(node.childNodes, length)
105
+ if alignlist:
106
+ for align in alignlist:
107
+ for k, v in mapping.items():
108
+ align[v] = node.attributes[k].value
109
+ if length:
110
+ align["query_length"] = length
111
+ isoForm = ""
112
+ if "db_code" in align and (align["db_code"].find("-") != -1):
113
+ tL = align["db_code"].split("-")
114
+ if len(tL) > 1 and len(tL[1]) > 0:
115
+ isoForm = str(tL[1]).strip()
116
+ dbCode = str(tL[0]).strip()
117
+ align["db_code"] = dbCode
118
+ if "db_accession" in align and (align["db_accession"].find("-") != -1):
119
+ tL = align["db_accession"].split("-")
120
+ if len(tL) > 1 and len(tL[1]) > 0:
121
+ isoForm = str(tL[1]).strip()
122
+ dbAcc = str(tL[0]).strip()
123
+ align["db_accession"] = dbAcc
124
+
125
+ align["db_isoform"] = isoForm
126
+ # Get uniprot sequence information
127
+
128
+ if "db_accession" in align:
129
+ fetchList.append(align["db_accession"])
130
+
131
+ resultlist.append(align)
132
+ #
133
+ # incorporate additional details about each matching sequence entry.
134
+ # -- DO NOT OVERWRITE EXISTING ANNOTATION other than db_code --
135
+ #
136
+ if len(fetchList) > 0:
137
+ fobj = FetchUnpXml(verbose=self.__verbose, log=self.__lfh)
138
+ fobj.fetchList(fetchList)
139
+ eD = fobj.getResult()
140
+ for align in resultlist:
141
+ if "db_accession" in align:
142
+ acId = align["db_accession"]
143
+ if acId in eD:
144
+ edict = eD[acId]
145
+ for k, v in edict.items():
146
+ if k == "db_code" or k not in align:
147
+ align[k] = v
148
+
149
+ return resultlist
150
+
151
+ def _ProcessAlignmentsTag(self, nodelist, length):
152
+ for node in nodelist:
153
+ if node.nodeType != node.ELEMENT_NODE:
154
+ continue
155
+ if node.tagName != "alignments":
156
+ continue
157
+ total = node.attributes["total"]
158
+ if total and total.value == "0":
159
+ continue
160
+
161
+ return self._ProcessAlignmentTag(node.childNodes, length)
162
+
163
+ return None # This is added for completeness due to warnings. Must never have fallen off end before
164
+
165
+ def _ProcessAlignmentTag(self, nodelist, length):
166
+ resultlist = []
167
+ for node in nodelist:
168
+ if node.nodeType != node.ELEMENT_NODE:
169
+ continue
170
+ if node.tagName != "alignment":
171
+ continue
172
+
173
+ rdict = self._GetMatchAlignment(node.childNodes, length)
174
+ if rdict:
175
+ resultlist.append(rdict)
176
+ return resultlist
177
+
178
+ @staticmethod
179
+ def _GetMatchAlignment(nodelist, query_length):
180
+ rdict = {}
181
+ for node in nodelist:
182
+ if node.nodeType != node.ELEMENT_NODE:
183
+ continue
184
+
185
+ if node.tagName == "identity":
186
+ rdict["identity"] = node.firstChild.data
187
+ elif node.tagName == "positives":
188
+ rdict["positive"] = node.firstChild.data
189
+ elif node.tagName == "gaps":
190
+ rdict["gaps"] = node.firstChild.data
191
+ elif node.tagName == "pattern":
192
+ rdict["midline"] = node.firstChild.data
193
+ elif node.tagName == "querySeq":
194
+ rdict["queryFrom"] = node.attributes["start"].value
195
+ rdict["queryTo"] = node.attributes["end"].value
196
+ rdict["query"] = node.firstChild.data
197
+ elif node.tagName == "matchSeq":
198
+ rdict["hitFrom"] = node.attributes["start"].value
199
+ rdict["hitTo"] = node.attributes["end"].value
200
+ rdict["subject"] = node.firstChild.data
201
+
202
+ if float(rdict["identity"]) < 70:
203
+ rdict.clear()
204
+ return rdict
205
+
206
+ if rdict:
207
+ if "query" in rdict:
208
+ rdict["alignLen"] = str(len(rdict["query"]))
209
+ if "queryFrom" in rdict and "queryTo" in rdict:
210
+ length = int(rdict["queryTo"]) - int(rdict["queryFrom"]) + 1
211
+ rdict["match_length"] = str(length)
212
+ if "identity" in rdict:
213
+ identity = int(math.ceil(float(length) * float(rdict["identity"]) / 100.0))
214
+ if query_length:
215
+ percent = identity * 100 / int(query_length)
216
+ if percent < 70:
217
+ rdict.clear()
218
+ return rdict
219
+ rdict["identity"] = str(identity)
220
+ if "positive" in rdict:
221
+ positive = int(math.ceil(float(length) * float(rdict["positive"]) / 100.0))
222
+ rdict["positive"] = str(positive)
223
+ if "gaps" in rdict:
224
+ gaps = int(math.ceil(float(length) * float(rdict["gaps"]) / 100.0))
225
+ rdict["gaps"] = str(gaps)
226
+ if "gaps" not in rdict:
227
+ rdict["gaps"] = "0"
228
+ return rdict
229
+
230
+
231
+ class ReadUnpBlastXmlFile(ReadUnpBlastXml):
232
+ """"""
233
+
234
+ def __init__(self, fileName, verbose=True, log=sys.stderr):
235
+ self._fileName = fileName
236
+ self._doc = minidom.parse(self._fileName) # noqa: S318
237
+ ReadUnpBlastXml.__init__(self, self._doc, verbose=verbose, log=log)
238
+
239
+
240
+ class ReadUnpBlastXmlString(ReadUnpBlastXml):
241
+ """"""
242
+
243
+ def __init__(self, data, verbose=True, log=sys.stderr):
244
+ self._data = data
245
+ self._doc = minidom.parseString(self._data) # noqa: S318
246
+ ReadUnpBlastXml.__init__(self, self._doc, verbose=verbose, log=log)
247
+
248
+
249
+ def main(argv): # pragma: no cover
250
+ opts, _args = getopt.getopt(argv, "x:", ["xml="])
251
+ for opt, arg in opts:
252
+ if opt in ("-x", "--xml"):
253
+ obj = ReadUnpBlastXmlFile(arg)
254
+ result = obj.GetResult()
255
+ for align in result:
256
+ for k, v in align.items():
257
+ sys.stdout.write("%s=%s\n" % (k, v))
258
+
259
+
260
+ if __name__ == "__main__": # pragma: no cover
261
+ try:
262
+ main(sys.argv[1:])
263
+ sys.exit(0)
264
+ except Exception as exc: # noqa: BLE001
265
+ sys.stderr.write("Exception: %s\n" % str(exc))
266
+ sys.exit(1)