-
Notifications
You must be signed in to change notification settings - Fork 2
/
uni2pandas.py
executable file
·192 lines (174 loc) · 6.04 KB
/
uni2pandas.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
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python
import click as ck
import numpy as np
import pandas as pd
import gzip
import logging
from utils import Ontology, is_exp_code, is_cafa_target, FUNC_DICT
import torch
logging.basicConfig(level=logging.INFO)
@ck.command()
@ck.option(
'--swissprot-file', '-sf', default='data/uniprot_sprot_2023_03.dat.gz',
help='UniProt/SwissProt knowledgebase file in text format (archived)')
@ck.option(
'--out-file', '-o', default='data/swissprot_exp_2023_03.pkl',
help='Result file with a list of proteins, sequences and annotations')
def main(swissprot_file, out_file):
go = Ontology('data/go-basic.obo', with_rels=True)
proteins, accessions, sequences, annotations, string_ids, orgs, genes, interpros = load_data(swissprot_file)
df = pd.DataFrame({
'proteins': proteins,
'accessions': accessions,
'genes': genes,
'sequences': sequences,
'annotations': annotations,
'string_ids': string_ids,
'orgs': orgs,
'interpros': interpros
})
logging.info('Filtering proteins with experimental annotations')
index = []
annotations = []
for i, row in enumerate(df.itertuples()):
annots = []
all_annots = []
for annot in row.annotations:
go_id, code = annot.split('|')
if is_exp_code(code):
annots.append(go_id)
all_annots.append(go_id)
# Ignore proteins without experimental annotations
if len(annots) == 0:
continue
index.append(i)
annotations.append(annots)
df = df.iloc[index]
df = df.reset_index()
df['exp_annotations'] = annotations
prop_annotations = []
for i, row in df.iterrows():
# Propagate annotations
annot_set = set()
annots = row['exp_annotations']
for go_id in annots:
annot_set |= go.get_ancestors(go_id)
annots = list(annot_set)
prop_annotations.append(annots)
df['prop_annotations'] = prop_annotations
esm2 = []
for i, row in enumerate(df.itertuples()):
prot_id = row.proteins
org = prot_id.split('_')[1]
esm_data = torch.load(f'data/esm15B/{org}/{prot_id}.pt')
esm2.append(esm_data['mean_representations'][48])
df['esm2'] = esm2
interpro2go = {}
gos = set()
with open('data/interpro2go.txt') as f:
for line in f:
if line.startswith('!'):
continue
it = line.strip().split()
ipr_id = it[0].split(':')[1]
go_id = it[-1]
if not go.has_term(go_id):
continue
if ipr_id not in interpro2go:
interpro2go[ipr_id] = set()
interpro2go[ipr_id].add(go_id)
gos.add(go_id)
gos = list(gos)
gos_df = pd.DataFrame({'gos': gos})
gos_df.to_pickle('data/interpro_gos.pkl')
ipr2go = []
for i, row in enumerate(df.itertuples()):
prot_id = row.proteins
annots = set()
for ipr in row.interpros:
if ipr in interpro2go:
annots |= interpro2go[ipr]
ipr2go.append(annots)
df['interpro2go'] = ipr2go
df.to_pickle(out_file)
logging.info('Successfully saved %d proteins' % (len(df),) )
def load_data(swissprot_file):
proteins = list()
accessions = list()
sequences = list()
annotations = list()
string_ids = list()
orgs = list()
genes = list()
interpros = list()
with gzip.open(swissprot_file, 'rt') as f:
prot_id = ''
seq = ''
org = ''
gene_id = ''
annots = list()
prot_ac = list()
strs = list()
iprs = list()
for line in f:
items = line.strip().split(' ')
if items[0] == 'ID' and len(items) > 1:
if prot_id != '':
proteins.append(prot_id)
accessions.append(prot_ac)
sequences.append(seq)
annotations.append(annots)
string_ids.append(strs)
orgs.append(org)
genes.append(gene_id)
interpros.append(iprs)
prot_id = items[1]
seq = ''
org = ''
gene_id = ''
annots = list()
prot_ac = list()
strs = list()
iprs = list()
elif items[0] == 'AC' and len(items) > 1:
prot_ac += [x.strip() for x in items[1].split(';') if x.strip() != '']
elif items[0] == 'OX' and len(items) > 1:
if items[1].startswith('NCBI_TaxID='):
org = items[1][11:]
end = org.find(' ')
org = org[:end]
else:
org = ''
elif items[0] == 'DR' and len(items) > 1:
items = items[1].split('; ')
if items[0] == 'GO':
go_id = items[1]
code = items[3].split(':')[0]
annots.append(go_id + '|' + code)
elif items[0] == 'STRING':
str_id = items[1]
strs.append(str_id)
elif items[0] == 'GeneID':
gene_id = items[1]
elif items[0] == 'InterPro':
ipr_id = items[1]
iprs.append(ipr_id)
elif items[0] == 'SQ':
seq = next(f).strip().replace(' ', '')
while True:
sq = next(f).strip().replace(' ', '')
if sq == '//':
break
else:
seq += sq
proteins.append(prot_id)
accessions.append(prot_ac)
sequences.append(seq)
annotations.append(annots)
string_ids.append(strs)
orgs.append(org)
genes.append(gene_id)
interpros.append(iprs)
return proteins, accessions, sequences, annotations, string_ids, orgs, genes, interpros
if __name__ == '__main__':
main()