-
Notifications
You must be signed in to change notification settings - Fork 2
/
sbi_project.py
575 lines (469 loc) · 25 KB
/
sbi_project.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# python modules
import Bio.PDB
#import numpy
import os
import sys
#import gzip
#import re
import collections as col
import copy
import argparse
import tarfile
import re
import ast
import warnings
#import shutil
from Bio import BiopythonWarning
# our modules
from functions import *
from classes import *
from reduce_inputs_func import *
from get_interactions import *
from DOPE_comparison import * #refine and compare
from DOPE_profile import * #plot energy of one model
import utilities
########################################################################################################################
######################################### Parser for command-line options ##############################################
########################################################################################################################
parser = argparse.ArgumentParser(description="Program to reconstruct a macrocomplex, given a set of interacting pairs "
"(prot-prot, prot-RNA).",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input',
dest="indir",
action="store",
default=None,
help="This is a directory provided by the user which contains the inputs pairs (compressed format is "
"also available .tar.gz). In case you want to rebuild a macrocomplex from PDB, you can introduce "
"its pdb file (.pdb).")
parser.add_argument('-o', '--output',
dest="outdir",
action="store",
default=None,
help="This is a directory which will be created during the program, structured in other subdirectories.")
parser.add_argument('-v', '--verbose',
dest="verbose",
action="store_true",
default=False,
help="This option will allow the user to completely follow the progam.")
parser.add_argument('-cc', '--clash_distance_cutoff',
dest="clash_distance_cutoff",
action="store",
type=float,
default=1.2,
choices=[0.25, 0.5, 1, 1.2, 1.5],
help="Choose a cut-off distance to detect clashes between chains.")
parser.add_argument('-e', '--energy_plot',
dest="energy_plot",
action="store_true",
default=False,
help="DOPE profile of the macrocomplex (not including nucleic acid chains) generated by Modeller.")
parser.add_argument('-ref', '--refine',
dest="refine",
action="store_true",
default=False,
help="Refines a model previously generated with the program according to the optimization parameters"
" defined by Modeller.")
parser.add_argument('-ver', '--version',
dest="version",
action="store",
type=str,
default="short",
choices=["short", "intensive"],
help="Short version only considers the first model the program can build, while Intensive version"
"considers all the possible models the program can build depending on the input pair it starts"
"the construction of the model.")
options = parser.parse_args()
########################################################################################################################
######################################### Getting and Organizing the inputs pairs ######################################
########################################################################################################################
print("\nSTARTING THE ANALYSIS\n\n")
# Avoid printing BiopythonWarnings
if options.verbose == False:
warnings.simplefilter('ignore', BiopythonWarning)
# Output directory
outputs_dir = options.outdir
# Reading inputs files from the user directory (considering .tar.gz)
inputs_dir = options.indir
user_dir = options.indir
p_tar_gz = re.compile(".+\.tar\.gz$")
if options.indir:
if p_tar_gz.match(options.indir):
inputs_tar = tarfile.open(options.indir)
inputs_tar.extractall()
inputs_dir = [x.name for x in inputs_tar][0]
inputs_files_path = [x.name for x in inputs_tar][1:]
inputs_files = [os.getcwd() + "/" + x for x in inputs_files_path]
elif os.path.isdir(options.indir):
inputs_dir = options.indir
inputs_files_path = os.listdir(inputs_dir)
inputs_files = [os.getcwd() + "/" + inputs_dir + "/" + x for x in
inputs_files_path] # this directory is the one provided by the user
elif options.indir.endswith(".pdb"):
if options.verbose:
sys.stderr.write("The program is getting all the possible pair interactions of the %s macrocomplex" % (inputs_dir))
inputs_dir = get_interactions(options.indir, outputs_dir)
inputs_files_path = os.listdir(inputs_dir)
inputs_files = [os.getcwd() + "/" + inputs_dir + x for x in
inputs_files_path]
if options.verbose:
sys.stderr.write("A directory named 'get_interactions_results' has been created here:\n %s\n" % (inputs_dir))
# Checking if the input directory is a directory.
try:
check_input(inputs_dir, user_dir)
except IncorrectInputDir as error:
print(str(error))
# Creating a directory (reduced_inputs) in the user output directory (outputs_dir), which contains reduced inputs from the
# user inputs (non-redundant interactions).
reduce_inputs_func(inputs_files, outputs_dir, options.verbose)
# Setting the directory where the files in reduced_inputs directory are.
inputs_reduced = outputs_dir + '/reduced_inputs/'
inputs_reduced_files = os.listdir(inputs_reduced)
if options.verbose:
sys.stderr.write("A directory named 'reduced_inputs' is created here:\n %s\n\n" % (inputs_reduced))
PDBparser = Bio.PDB.PDBParser()
# Creating a list of dictionaries with the pairs of the inputs. The key is the object with the id changed to numbers
# for handeling the limitation of letters (<chain1>) and the value the id from the pdb file (A).
list_of_dic_inputs = []
c = 0
for pair in inputs_reduced_files:
chain_pair_dic = {}
pdb_code = pair
pdb_filename = inputs_reduced + pair # .pdb
structure = PDBparser.get_structure(pdb_code, pdb_filename)
for model in structure:
for chain in model:
c += 1
original_id = copy.copy(chain.id)
chain.id = c
chain_pair_dic[chain] = original_id
list_of_dic_inputs.append(chain_pair_dic)
# List of tuples where the first element is the chain object and the second, its sequence
chain_seq_list = []
for dic in list_of_dic_inputs:
chain_seq = tuple()
for key in dic:
chain_seq = (key, get_seq_from_pdbchain(key))
chain_seq_list.append(chain_seq)
if options.verbose:
sys.stderr.write("Making pairwise comparisons between all the inputs to create a dictionary of chains equivalences\n")
# Making pairwise comparisons between all the inputs to create a dictionary of equivalences (chains_eq_dic).
# Creating the alignment_results.txt file in the user output directory (outputs_dir)
chains_eq_dic = {}
alignments_results = open(outputs_dir + "/alignments_results.txt", "w")
cutoff = 0.9
cutoff_list = []
for element in chain_seq_list:
element_len = len(element[1])
for element2 in chain_seq_list:
element2_len = len(element2[1])
alignments_results.write("This is the alignment between: %s and %s: " % (element, element2))
alignments = pairwise2.align.globalxx(element[1], element2[1])
if len(alignments) > 0:
score_chain = alignments[0][2]
len_max = max(element_len, element2_len)
cutoff_chain = score_chain / len_max
info = (element[0], element2[0], cutoff_chain)
cutoff_list.append(info)
if cutoff_chain >= cutoff:
alignments_results.write("\tThe max score is %d\n" % (alignments[0][2]))
chains_eq_dic[element[0]] = element2[0]
break
else:
alignments_results.write("\tNO ALIGNMENT\n")
alignments_results.close()
if options.verbose:
sys.stderr.write("You can find more information about this steps in 'alignments_results.txt' file here:\n %s\n\n" % (alignments_results.name))
if options.verbose:
sys.stderr.write("Determining the unique chains to be able to decide the stoichiometry later.\n")
# Set that will contain the unique chains of the complex
unique_chains = set(chains_eq_dic.values())
if options.verbose:
sys.stderr.write("The program has found %d unique chains.\n" % (len(unique_chains)))
# Assignation of a letter to the unique chains to show them to the user and obtain the stoichiometry as a dictionary (number_to_letter)
number_to_letter = {}
for ch in unique_chains:
number_to_letter[ch] = ""
for character in utilities.ascii_list:
if character not in number_to_letter.values():
number_to_letter[ch] = character
break
# Multifasta file containing the unique chains. It will be created as unique_chains_fasta.mfa in the user output directory (outputs_dir),
# to allow the user to introduce the stoichiometry of the macrocomplex.
unique_chains_mfa = unique_chains_fasta(number_to_letter, outputs_dir)
if options.verbose:
sys.stderr.write("A multifasta file named 'unique_chains_fasta.mfa' of the unique chains has been created here: \n %s\n" % (unique_chains_mfa.name))
# Getting the stoichiometry from the user
while True:
print("Check the unique_chains_fasta.mfa file to decide the stoichiometry of the macrocomplex.\n ")
print("PLEASE ENTER THE STOICHIOMETRY\nIn this format: {'a': 1, 'b': 1, 'c': 2}\n ")
try:
a = input("Please enter the stoichiometry dictionary: ")
ref_counter_user = ast.literal_eval(a)
except ValueError:
print("Something went wrong, try again...\n")
continue
except SyntaxError:
print("Something went wrong, try again...\n")
continue
else:
if isinstance(ref_counter_user, dict) == False:
print("Something went wrong, try again...\n")
continue
break
if options.verbose:
sys.stderr.write("The stoichiometry dictionary has correctly been introduced.\n")
# Resetting the value (chain id) of the list_of_dic_inputs keys to its equivalence (obtained above by pairwise alignment)
list_of_dic = []
for dic in list_of_dic_inputs:
dic_pair = {}
for key, value in dic.items():
for key2, value2 in chains_eq_dic.items():
if key == key2:
for key3, value3 in number_to_letter.items():
if value2 == key3:
dic_pair[key] = value3
list_of_dic.append(dic_pair)
# Converting the list (list_of_dic) into a dictionary (allchains)
allchains = {}
for d in list_of_dic:
for k, v in d.items():
allchains[k] = v
# Preventing from problems with clashes (avoiding infinite loops)
n_chains = sum(ref_counter_user.values())
n_pairs = len(list_of_dic)
threshold_clashes = n_chains * 2 * n_pairs
########################################################################################################################
############################################### Construction of the models #############################################
########################################################################################################################
print("\n### STARTING THE CONSTRUCTION OF THE MACROCOMPLEX... Please wait.\n")
# Cut-off distance to detect clashes
clash_distance_cutoff = options.clash_distance_cutoff
# Creating a subdirectory (models) in the user output directory (outputs_dir), which will containg all the models
output_models = (outputs_dir + "/models/")
if not os.path.exists(output_models):
os.makedirs(output_models)
# Creating as many models as inputs are in the reduced_inputs directory, through iterating among the list_of_dic.
n_model = 0
model_number = 0
for input in list_of_dic:
n_model += 1
if options.verbose:
sys.stderr.write("\n# Trying to build the model %d\n" % (n_model))
n_round = 0
clash_count = 0
# Selecting the pair of chains that will be the initial reference chains to build the model (ref_counter_chains)
input_idx = list_of_dic.index(input)
ref_counter_chains = copy.copy(list_of_dic[input_idx])
# Change ids of the reference chains (from numbers to letters) to save the model (.pdb) with a uniform format.
input_ids = ["a", "b"]
i = 0
for k, v in copy.copy(list_of_dic[input_idx]).items():
k.id = input_ids[i]
i += 1
# Creating the current model with the reference chains
current_model = Bio.PDB.Model.Model(model_number)
for chain in copy.copy(list_of_dic[input_idx]).keys():
current_model.add(chain)
# Adding the model to the list of models
list_models = [current_model]
# Define initial stoichiometry counter from the stoichiometry introduced by the user (ref_counter_user)
ref_counter = {}
for ids, count in ref_counter_user.items():
ref_counter[ids] = count
i = count
for key, value in copy.copy(list_of_dic[input_idx]).items():
if value == ids:
i -= 1
ref_counter[ids] = i
# Selecting all other input pairs (total_list) except from the reference input pair (ref_chains)
ref_chains = copy.copy(list_of_dic[input_idx])
idx = list_of_dic.index(ref_chains)
total_list = list_of_dic[:idx] + list_of_dic[idx + 1:]
# Checking the number of chains in ref_chains and in total_list to ensure that the model can be build based on the
# stoichiometry
# Counting of ref_chains
ref_chains_count = {}
for v in ref_chains.values():
if not v in ref_chains_count:
ref_chains_count[v] = 1
else:
ref_chains_count[v] += 1
# Creation and counting of total_dict
total_dict = {}
for x in total_list:
for k, v in x.items():
total_dict[k] = v
total_dict_count = {}
for ch, letter in allchains.items():
total_dict_count[letter] = 0
for v in total_dict.values():
if v not in total_dict_count:
total_dict_count[v] = 1
else:
total_dict_count[v] += 1
# Checking the actual counts
check_input = 0
for k, v in ref_chains.items():
if ref_counter[v] == 0:
check_input += 1
elif ref_counter[v] >= 1:
if ref_chains_count[v] == 2 or total_dict_count[v] >= 1:
check_input += 1
if check_input == 2:
# Defining a boolean flag (run) to check if there are still remaining chains to be added to the model.
run = True
while run == True:
# Iterating through each dictionary (alt_chains) of the total_list
for alt_chains in total_list:
# Iterating through each chain of ref_chains to compare it with the current dictionary (alt_chains)
for key, value in ref_chains.items():
n_round += 1
for element in alt_chains:
# Checking if the ids from the current compared chains (ref_chains vs. alt_chains) are equal
# to proceed with the analysis
if value == alt_chains[element]:
# Defining variables for the further superimposition (fixedchain, movingchain and altchain)
fixedchain = key
movingchain = element
alt_chains_copy = col.OrderedDict(alt_chains)
del alt_chains_copy[movingchain]
altchain = list(alt_chains_copy)[0]
# Saving actual altchain (i_chain) to lately check it in the counter
i_chain = alt_chains[altchain]
for ele in ref_counter:
# Checking if there are still chains with the same id as i_chain to be added to the model
if ref_counter[i_chain] != 0:
# Getting atoms list for the superimposition
fixed_atoms_list = get_atoms_list(fixedchain)
moving_atoms_list = get_atoms_list(movingchain)
alt_atoms_list = get_atoms_list(altchain)
# Creating a list with the used ids (letters) of the current model chains. Using
# this list to control the "same id error" when adding a new chain
used_letters_list = [x.id for x in current_model]
# If the length exceeds the maximum different characters available, a new empty
# model will be created to be able to add chains avoiding this error
if len(used_letters_list) == 83:
list_models.append(current_model)
io = Bio.PDB.PDBIO()
io.set_structure(current_model)
model_number += 1
current_model = Bio.PDB.Model.Model(model_number)
used_letters_list = []
# Creating a copy of the altchain to add it with a new avaiable id
for character in utilities.ascii_list:
if character not in used_letters_list:
new_id = character
break
new_chain = Bio.PDB.Chain.Chain(new_id)
altchain = copy.copy(altchain)
for residue in altchain.get_residues():
new_chain.add(residue.copy())
current_model.add(new_chain)
# Comparing number of atoms from fixed and moving chain. If it is different,
# refining the lists to obtain equal lenght
if len(fixed_atoms_list) != len(moving_atoms_list):
chains_pattern = refine_for_superimpose(fixedchain, movingchain)
fixed_pattern = chains_pattern[0]
moving_pattern = chains_pattern[1]
fixedchain = get_chain_refined(fixedchain, fixed_pattern)
movingchain = get_chain_refined(movingchain, moving_pattern)
fixed_atoms_list = get_atoms_list(fixedchain)
moving_atoms_list = get_atoms_list(movingchain)
# Superimposing the chains
super_imposer = Bio.PDB.Superimposer()
super_imposer.set_atoms(fixed_atoms_list, moving_atoms_list)
super_imposer.apply(new_chain.get_atoms())
# Checking if the added chain clashes with any chain of the current model. If it
# clashes it will be detached
clash = check_clashes_multi(current_model, list_models, new_chain,
clash_distance_cutoff)
if clash == True:
clash_count += 1
current_model.detach_child(new_chain.id)
break
if options.verbose:
sys.stderr.write("\tA new chain has been added to the model.\n")
# Actualize ref_conter_chains (adding i_chain)
ref_counter_chains[new_chain] = i_chain
# Actualize ref_counter considering the previously added i_chain
for ids, count in ref_counter.items():
if ids == i_chain:
i = count
if i != 0:
i -= 1
ref_counter[i_chain] = i
if options.verbose:
sys.stderr.write("\tThe following chains has not been yet included in the model:\n\t %s\n " % ref_counter)
break
if clash_count >= threshold_clashes:
print("\nSomething went wrong...\n")
if options.version == "intensive":
sys.stderr.write("Trying to reconstruct the model from the following input.\n")
break
ref_chains = copy.copy(ref_counter_chains)
# Resetting the flag (run) to False. If there are still chains to be added, it is turned to True, and the while loop
# continues
run = False
for ch, n in ref_counter.items():
if n != 0:
run = True
break
if clash_count >= threshold_clashes:
if options.version == "short":
sys.stderr.write("Try the intensive version (-ver or --version intensive) or select another clash cut-off (-cc or --clash_distance_cutoff).\n")
exit()
else:
# Save the final model (with all the chains). In case the model has more than 83 chains, another model is created
# to avoid problems with chain ids.
print("\nSAVING MODEL %d...\n" % n_model)
# Adding only current_model if it is not yet in the list_models
list_models.append(current_model)
set_models = set(list_models)
# Creating a subdirectory (outputs) of the models directory, for each one of the models.
outputs = (output_models + str(n_model) + "/")
if not os.path.exists(outputs):
os.makedirs(outputs)
mod = 0
for model in set_models:
model_filename = n_model
pdb_model_filename = outputs + str(model_filename) + "_" + str(mod) + ".aligned.pdb"
io = Bio.PDB.PDBIO()
io.set_structure(model)
io.save(pdb_model_filename)
mod += 1
print("The model '%s' has been saved here:\n %s\n\n" % (pdb_model_filename, outputs))
if options.energy_plot:
# Preparing for the energy analysis (Modeller) -> creating outputs/temp/_mod.pdb
temp_dir = create_tempPDB(outputs)
# DOPE profile plot for each model
blockPrint()
DOPE_energy_plot=DOPE_profiles_maker(temp_dir, outputs)
enablePrint()
print(DOPE_energy_plot)
if options.refine:
print("Starting to refine the models. This step may take a few minutes...\n")
refined_models = outputs + "optimization_results/refined_models/"
if not os.path.exists(refined_models):
os.makedirs(refined_models)
stats = outputs + "optimization_results/stats/"
if not os.path.exists(stats):
os.makedirs(stats)
dope_profile = outputs + "optimization_results/dope_profile/"
if not os.path.exists(dope_profile):
os.makedirs(dope_profile)
log_files = outputs + "optimization_results/log_files/"
if not os.path.exists(log_files):
os.makedirs(log_files)
if options.verbose:
sys.stderr.write("The following directories will be created:\n %s\n %s\n %s\n %s\n\n" % (refined_models, stats, dope_profile, log_files))
refine_model(outputs, log_files, stats, refined_models, dope_profile)
models_dir = create_tempPDB(outputs)
refined_comparison = refined_vs_notrefined(models_dir, dope_profile)
print(refined_comparison)
if options.verbose:
sys.stderr.write("You can find detailed information about the refining process in the log file.\n")
if options.version != "short":
continue
else:
break
print("\n\nTHE CONSTRUCTION PROCESS HAS ENDED\n")