fatmacankara commited on
Commit
a999cff
·
1 Parent(s): 50482d6

Create swissModelAdd.py

Browse files
Files changed (1) hide show
  1. code/swissModelAdd.py +209 -0
code/swissModelAdd.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from pathlib import Path
4
+ import requests
5
+ from add_annotations import *
6
+ from utils import *
7
+ from add_annotations import *
8
+ from add_sasa import *
9
+ import streamlit as st
10
+ import json
11
+
12
+ UNIPROT_ANNOTATION_COLS = ['disulfide', 'intMet', 'intramembrane', 'naturalVariant', 'dnaBinding',
13
+ 'activeSite',
14
+ 'nucleotideBinding', 'lipidation', 'site', 'transmembrane',
15
+ 'crosslink', 'mutagenesis', 'strand',
16
+ 'helix', 'turn', 'metalBinding', 'repeat', 'topologicalDomain',
17
+ 'caBinding', 'bindingSite', 'region',
18
+ 'signalPeptide', 'modifiedResidue', 'zincFinger', 'motif',
19
+ 'coiledCoil', 'peptide',
20
+ 'transitPeptide', 'glycosylation', 'propeptide', 'disulfideBinary',
21
+ 'intMetBinary', 'intramembraneBinary',
22
+ 'naturalVariantBinary', 'dnaBindingBinary', 'activeSiteBinary',
23
+ 'nucleotideBindingBinary', 'lipidationBinary', 'siteBinary',
24
+ 'transmembraneBinary', 'crosslinkBinary', 'mutagenesisBinary',
25
+ 'strandBinary', 'helixBinary', 'turnBinary', 'metalBindingBinary',
26
+ 'repeatBinary', 'topologicalDomainBinary', 'caBindingBinary',
27
+ 'bindingSiteBinary', 'regionBinary', 'signalPeptideBinary',
28
+ 'modifiedResidueBinary', 'zincFingerBinary', 'motifBinary',
29
+ 'coiledCoilBinary', 'peptideBinary', 'transitPeptideBinary',
30
+ 'glycosylationBinary', 'propeptideBinary']
31
+ SIMPLE_COLS = ['uniprotID', 'wt', 'pos', 'mut', 'datapoint', 'composition', 'polarity',
32
+ 'volume', 'granthamScore', 'domain', 'domStart', 'domEnd', 'distance',
33
+ 'intMet', 'naturalVariant', 'activeSite', 'crosslink', 'mutagenesis',
34
+ 'strand', 'helix', 'turn', 'region', 'modifiedResidue', 'motif',
35
+ 'metalBinding', 'lipidation', 'glycosylation', 'topologicalDomain',
36
+ 'nucleotideBinding', 'bindingSite', 'transmembrane', 'transitPeptide',
37
+ 'repeat', 'site', 'peptide', 'signalPeptide', 'disulfide', 'coiledCoil',
38
+ 'intramembrane', 'zincFinger', 'caBinding', 'propeptide', 'dnaBinding',
39
+ 'disulfideBinary', 'intMetBinary', 'intramembraneBinary',
40
+ 'naturalVariantBinary', 'dnaBindingBinary', 'activeSiteBinary',
41
+ 'nucleotideBindingBinary', 'lipidationBinary', 'siteBinary',
42
+ 'transmembraneBinary', 'crosslinkBinary', 'mutagenesisBinary',
43
+ 'strandBinary', 'helixBinary', 'turnBinary', 'metalBindingBinary',
44
+ 'repeatBinary', 'topologicalDomainBinary', 'caBindingBinary',
45
+ 'bindingSiteBinary', 'regionBinary', 'signalPeptideBinary',
46
+ 'modifiedResidueBinary', 'zincFingerBinary', 'motifBinary',
47
+ 'coiledCoilBinary', 'peptideBinary', 'transitPeptideBinary',
48
+ 'glycosylationBinary', 'propeptideBinary']
49
+
50
+ def addSwissModels(to_swiss, path_to_input_files, path_to_output_files):
51
+ '''
52
+ :param to_swiss:
53
+ :param path_to_input_files:
54
+ :param path_to_output_files:
55
+ :return: swissmodel dataframe with mapped SWISSMODEL information, dataframe that will be sent to modbase.
56
+ '''
57
+
58
+ print('\n>>> Proceeding to SwissModel search...')
59
+ print('------------------------------------\n')
60
+
61
+ if len(to_swiss) > 0:
62
+ print('\n>>> Generating SwissModel file...\n')
63
+
64
+ to_swiss.reset_index(drop=True, inplace=True)
65
+ to_swiss.fillna(np.NaN)
66
+
67
+ swiss_model = pd.read_csv(Path(path_to_input_files / 'swissmodel_structures.txt'),
68
+ sep='\t', dtype=str, header=None, skiprows=1,
69
+ names=['UniProtKB_ac', 'iso_id', 'uniprot_seq_length', 'uniprot_seq_md5',
70
+ 'coordinate_id', 'provider', 'from', 'to', 'template', 'qmean_norm', 'seqid',
71
+ 'url'])
72
+ swiss_model = swiss_model[swiss_model.UniProtKB_ac.isin(to_swiss.uniprotID.to_list())]
73
+ try:
74
+ swiss_model.iso_id = swiss_model.iso_id.astype('str')
75
+ except:
76
+ AttributeError
77
+ swiss_model['iso_id'] = np.NaN
78
+ for ind in swiss_model.index:
79
+ swiss_model.at[ind, 'UniProtKB_ac'] = swiss_model.at[ind, 'UniProtKB_ac'].split('-')[0]
80
+ swiss_model = swiss_model[swiss_model.provider == 'SWISSMODEL']
81
+ print('\n>>> Index File Processed...\n')
82
+ swiss_model = swiss_model[['UniProtKB_ac', 'from', 'to', 'template', 'qmean_norm', 'seqid', 'url']]
83
+ # Sort models on qmean score and identity. Some proteins have more than one models, we will pick one.
84
+ swiss_model = swiss_model.sort_values(by=['UniProtKB_ac', 'qmean_norm', 'seqid'], ascending=False)
85
+ swiss_model.reset_index(inplace=True, drop=True)
86
+ with_swiss_models = to_swiss[to_swiss.uniprotID.isin(swiss_model.UniProtKB_ac.to_list())]
87
+ no_swiss_models = to_swiss[~to_swiss.uniprotID.isin(swiss_model.UniProtKB_ac.to_list())]
88
+ if len(no_swiss_models) == 0:
89
+ no_swiss_models = pd.DataFrame(columns=to_swiss.columns)
90
+ else:
91
+ no_swiss_models.reset_index(drop=True, inplace= True)
92
+
93
+ swiss_models_with_data = pd.merge(with_swiss_models, swiss_model, left_on=['uniprotID'],
94
+ right_on=['UniProtKB_ac'], how='left')
95
+
96
+ swiss_models_with_data = swiss_models_with_data.sort_values(by=['uniprotID', 'wt','pos', 'qmean_norm'],
97
+ ascending=False)
98
+
99
+ swiss_models_with_data['pos'] = swiss_models_with_data['pos'] .apply(lambda x: int(x))
100
+ swiss_models_with_data['from'] = swiss_models_with_data['from'].apply(lambda x: int(x))
101
+ swiss_models_with_data['to'] = swiss_models_with_data['to'] .apply(lambda x: int(x))
102
+
103
+ notEncompassed = swiss_models_with_data[((swiss_models_with_data['pos'] > swiss_models_with_data['to']) | (swiss_models_with_data['pos'] < swiss_models_with_data['from']))]
104
+ swiss_models_with_data = swiss_models_with_data[(swiss_models_with_data['pos'] < swiss_models_with_data['to']) & (swiss_models_with_data['pos'] > swiss_models_with_data['from'])]
105
+
106
+ notEncompassed = notEncompassed[~notEncompassed.uniprotID.isin(swiss_models_with_data.uniprotID.to_list())]
107
+ swiss_models_with_data = swiss_models_with_data.drop(['UniProtKB_ac', 'seqid'], axis=1)
108
+ swiss_models_with_data = swiss_models_with_data[swiss_models_with_data.url != np.NaN]
109
+ url_nan = swiss_models_with_data[swiss_models_with_data.url == np.NaN]
110
+ url_nan = url_nan.drop(['from', 'qmean_norm', 'template', 'to', 'url'], axis=1)
111
+
112
+
113
+ no_swiss_models_updated = pd.concat([no_swiss_models, url_nan, notEncompassed])
114
+ if len(swiss_models_with_data)>0:
115
+ for i in swiss_models_with_data.index:
116
+ try:
117
+ swiss_models_with_data.at[i, 'chain'] = swiss_models_with_data.at[i, 'template'].split('.')[2]
118
+ swiss_models_with_data.at[i, 'template'] = swiss_models_with_data.at[i, 'template'].split('.')[0]
119
+ except IndexError:
120
+ swiss_models_with_data.at[i, 'chain'] = np.NaN
121
+ swiss_models_with_data.at[i, 'template'] = np.NaN
122
+
123
+ swiss_models_with_data.chain = swiss_models_with_data.chain.astype('str')
124
+ swiss_models_with_data['qmean_norm'] = swiss_models_with_data.qmean_norm.apply(lambda x: round(float(x), 2))
125
+
126
+ no_swiss_models_updated.reset_index(drop = True, inplace=True)
127
+ swiss_models_with_data.reset_index(drop=True, inplace=True)
128
+
129
+ existing_free_sasa = list(Path(path_to_output_files / 'freesasa_files').glob("*"))
130
+ existing_free_sasa = [str(i) for i in existing_free_sasa]
131
+ existing_free_sasa = [i.split('/')[-1].split('.')[0] for i in existing_free_sasa]
132
+ print('Beginning SwissModel files download...')
133
+ existing_swiss = list(Path(path_to_output_files / 'swissmodel_structures').glob("*"))
134
+ existing_swiss = [str(i) for i in existing_swiss]
135
+ existing_swiss = ['.'.join(i.split('/')[-1].split('.')[:-1]) for i in existing_swiss]
136
+
137
+ for i in swiss_models_with_data.index:
138
+ protein = swiss_models_with_data.at[i, 'uniprotID']
139
+ varPos = swiss_models_with_data.at[i, 'pos']
140
+ wt = swiss_models_with_data.at[i, 'wt']
141
+ template = swiss_models_with_data.at[i, 'template'].split('.')[0]
142
+ qmean_norm = str(round(float(swiss_models_with_data.at[i, 'qmean_norm']), 2))
143
+
144
+ swiss_models_with_data.at[i, 'coordVAR'] = np.NaN
145
+ swiss_models_with_data.at[i, 'coordinates'] = np.NaN
146
+ swiss_models_with_data.at[i, 'AAonPDB'] = np.NaN
147
+ varPos = swiss_models_with_data.at[i, 'pos']
148
+ AAonPDB = np.NaN
149
+ coordDict = {}
150
+ if protein + '_' + template + '_' + qmean_norm not in existing_swiss:
151
+ url = swiss_models_with_data.at[i, 'url'].strip('\"').strip('}').replace('\\', '').strip('\"')
152
+ req = requests.get(url)
153
+ name = Path(path_to_output_files / 'swissmodel_structures' / f'{protein}_{template}_{qmean_norm}.txt')
154
+ print('Downloading for Protein:', protein + ' Model: ' + template)
155
+ with open(name, 'wb') as f:
156
+ f.write(req.content)
157
+ else:
158
+ print(f'Model exists for {protein}.')
159
+ name = Path(path_to_output_files / 'swissmodel_structures' / f'{protein}_{template}_{qmean_norm}.txt')
160
+
161
+ swiss_dp = protein + '_' + template + '_' + qmean_norm
162
+ if swiss_dp not in existing_free_sasa:
163
+
164
+ (run_freesasa(Path(path_to_output_files / 'swissmodel_structures' / f'{swiss_dp}.txt'),
165
+ Path(path_to_output_files / 'freesasa_files' / f'{swiss_dp}.txt'), include_hetatms=True,
166
+ outdir=None, force_rerun=False, file_type='pdb'))
167
+
168
+ filename = Path(path_to_output_files / 'freesasa_files' / f'{swiss_dp}.txt')
169
+
170
+ swiss_models_with_data.at[i, 'sasa'] = sasa(protein, varPos, wt, 1, filename, path_to_output_files,
171
+ file_type='pdb')
172
+ with open(name, encoding="utf8") as f:
173
+ lines = f.readlines()
174
+ for row in lines:
175
+ if row[0:4] == 'ATOM' and row[13:15] == 'CA':
176
+ position = int(row[22:26].strip())
177
+ chain = row[20:22].strip()
178
+ aminoacid = threeToOne(row[17:20])
179
+ coords = [row[31:38].strip(), row[39:46].strip(), row[47:54].strip()]
180
+ coordDict[position] = coords
181
+ if int(position) == int(varPos):
182
+ AAonPDB = aminoacid
183
+ coordVAR = coords
184
+ if (row[0:3] == 'TER') or (row[0:3] == 'END'):
185
+
186
+ swiss_models_with_data.loc[i, 'coordinates'] = str(coordDict)
187
+ swiss_models_with_data.loc[i, 'AAonPDB'] = str(AAonPDB)
188
+ swiss_models_with_data.loc[i, 'coordVAR'] = str(coordVAR)
189
+
190
+ break
191
+
192
+ if swiss_models_with_data.at[i, 'AAonPDB'] == swiss_models_with_data.at[i, 'wt']:
193
+ swiss_models_with_data.at[i, 'PDB_ALIGN_STATUS'] = 'aligned'
194
+ else:
195
+ swiss_models_with_data.at[i, 'PDB_ALIGN_STATUS'] = 'notAligned'
196
+ swiss_models_with_data.sort_values(['uniprotID', 'wt', 'pos', 'mut', 'PDB_ALIGN_STATUS', 'qmean_norm'],
197
+ ascending=[True, True, True, True, True, False], inplace=True)
198
+ swiss_models_with_data.drop_duplicates(['uniprotID', 'wt', 'pos', 'mut'], keep='first', inplace=True)
199
+ obsolete = swiss_models_with_data[pd.isna(swiss_models_with_data.coordVAR)]
200
+ no_swiss_models_updated = pd.concat([no_swiss_models_updated, obsolete])
201
+ swiss_models_with_data = swiss_models_with_data.fillna(np.NaN)
202
+ else:
203
+ swiss_models_with_data = pd.DataFrame()
204
+ no_swiss_models_updated = pd.DataFrame()
205
+
206
+ no_swiss_models_updated = no_swiss_models_updated[SIMPLE_COLS]
207
+ return swiss_models_with_data, no_swiss_models_updated
208
+
209
+