-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBetaTurnTool18.py2
1606 lines (1439 loc) · 92.2 KB
/
BetaTurnTool18.py2
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# ########
# Platform
# ########
#
# Supported on Unix/Mac/Windows with Python 2
# #########
# Execution
# #########
# This program is written for Python 2 which is more common.
# Please make sure you are running this program with Python 2, NOT Python 3.
# 'python' from your terminal needs to link to Python 2, NOT Python 3.
#
# For execution from a terminal, you may try:
#
# Unix/Mac/Windows:
# -----------------
# python BetaTurnTool18.py2
# python2 BetaTurnTool18.py2
#
# Unix/Mac:
# ---------
# /usr/bin/python BetaTurnTool18.py2
# /usr/bin/python2 BetaTurnTool18.py2
# /usr/bin/env python BetaTurnTool18.py2
# /usr/bin/env python2 BetaTurnTool18.py2
#
# For Shebang (Hashbang) in Unix/Mac:
# -----------------------------------
# Make sure in the top line 'python' links to Python 2 and NOT Python 3
# If Python 2 is linked with python2, please modify the top line to "#!/usr/bin/env python2"
#
# Windows:
# --------
# C:\Python\python.exe BetaTurnTool18.py2
# #######
# License
# #######
# Copyright (c) 2018-2019, Maxim Shapovalov (1,2), Slobodan Vucetic (2), Roland L. Dunbrack, Jr. (1,^)
# All rights reserved.
#
# (1): Fox Chase Cancer Center, 333 Cottman Avenue, Philadelphia PA 19111, USA
# (2): Temple University, 1801 N Broad Street, Philadelphia PA 19122, USA
# (^): Corresponding Author, Roland dot Dunbrack at fccc dot edu
#
# BSD 3-Clause License
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
import sys
global glob_operating_system; glob_operating_system = 'unix'
global glob_operating_system_full; glob_operating_system_full = 'Unix'
#detection of operating system family
_platform = sys.platform.lower()
if "linux" in _platform or "unix" in _platform:
glob_operating_system = 'unix'
glob_operating_system_full = 'Unix'
elif "darwin" in _platform or "mac" in _platform:
glob_operating_system = 'mac'
glob_operating_system_full = 'Mac OS'
elif "win" in _platform:
glob_operating_system = 'win'
glob_operating_system_full = 'Windows'
#automatic installation of required python packages in Unix/Mac/Windows
_required_packages = [['Bio','biopython'], ['numpy','numpy']]
for _package in _required_packages:
try:
exec(_package[0] + " = __import__(_package[0])")
except ImportError as e:
try:
print ".................................................................................."
print "..... Your operating system family is detected as \'%s\'" % glob_operating_system_full
print "..... Automatically installing required python2 module, \'%s\'" % _package[1]
import pip
try:
from pip import main as pipmain
print "..... Older version of python module installer, \'pip\' is detected"
except ImportError:
from pip._internal import main as pipmain
print "..... Newer version of python module installer, \'pip\' is detected"
print ".................................................................................."
if glob_operating_system == 'win':
_user_is_admin = False
try:
import ctypes
_user_is_admin = (ctypes.windll.shell32.IsUserAnAdmin() != 0)
except:
print "..... Could not determine for sure whether you ARE or ARE NOT an administrator on this computer."
print "..... Installation will proceed assuming you are NOT an administrator."
if _user_is_admin == True:
print "..... You ARE an administrator of this computer."
print "..... Therefore trying to install the module systemwide"
print ".................................................................................."
pipmain(['install', _package[1]])
else:
print "..... You are NOT an administrator of this computer."
print "..... Therefore trying to install the module locally in your Documents directory"
print ".................................................................................."
pipmain(['install', '--user', _package[1]])
elif glob_operating_system in ['unix', 'mac']:
import os
if os.geteuid() == 0:
print "..... You HAVE root previliges."
print "..... Therefore trying to install the module systemwide"
print ".................................................................................."
pipmain(['install', _package[1]])
else:
print "..... You do NOT have root previliges."
print "..... Therefore trying to install the module locally in your home directory"
print ".................................................................................."
pipmain(['install', '--user', _package[1]])
print ".................................................................................."
exec(_package[0] + " = __import__(_package[0])")
except Exception as _e:
print "*****************************************************"
print "*** The program automatically attempted to install a required python2 module, \'%s\'." % _package[1]
print "*** "
print "*** (1) If the module installation was successful, run this program again."
print "*** (2) If (1) was unsuccesful, run this program again with root previliges (sudo)."
print "*** (3) If both (1) and (2) are unsuccessful, please install a required python2 module \'%s\' yourself" % _package[1]
print "*** by issuing one of the following commands and then try again:"
print " "
print " apt-get install python-%s" % _package[1]
print " sudo apt-get install python-%s" % _package[1]
print " pip2 install %s" % _package[1]
print " sudo pip2 install %s" % _package[1]
print " pip install %s" % _package[1]
print " sudo pip install %s" % _package[1]
print " "
print " (4) If all three (1), (2) and (3) are unsuccesful, please review the following technical details:"
print " "
print " Exception details:"
print " ~~~~~~~~~~~~~~~~~~"
print " %s" % _e
print " (this error message might be incorret -- please try again)"
exit(1)
#by this line all required python libraries must have been already installed
import os
import csv
import math
import warnings
import argparse
import re
#biopython library components
import Bio.PDB
import Bio.SeqIO
import Bio.pairwise2
#main entry point of the program
def main():
#declaring global variables and setting their default values
global glob_fpath_script; glob_fpath_script = os.path.realpath(__file__)
global glob_fpath_script_dir; glob_fpath_script_dir = os.path.split(glob_fpath_script)[0]
global glob_fPath_dssp_binary
global glob_fPath_BetaTurnLib
global glob_BetaTurnLib_version; glob_BetaTurnLib_version = '-1.-1.-1'
global glob_bTurnLibListOfDict
global glob_default_bturn_library_filename; glob_default_bturn_library_filename = r'BetaTurnLib18.txt'
global glob_border_confidence_value; glob_border_confidence_value = 0.70
global glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other
#This maximum distance is equal to the mean plus 3 standard deviations of
#12,711 distances between turns of one of 18 types (Other excluded) to
#their cluster medoids, which is equal to 0.2359 in units of our distance metric
#or 28.1 deg in units of the average angle equivalent of our metric.
glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other = 0.052794243055754 + 3 * 0.061032309981708
global CA1CA4_beta_turn_distance_cutoff
global global_SkipProcessingOfAlternativeConformations
#This option is now disabled in official arguments, it is kept here in code, just in case, it is always False
global_SkipProcessingOfAlternativeConformations = False
#For macOS only: for newer versions of DSSP need to specify a location for dynamically linked libraries of Boost library
if glob_operating_system == 'mac':
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = os.path.join(glob_fpath_script_dir, 'DSSP', 'Lib_macOS')
#setting up expected input arguments
myArgParser = argparse.ArgumentParser(add_help=False)
myArgParser.add_argument("-i", "--input", help='for example, -i abcd.cif or --input abcd.pdb')
myArgParser.add_argument("-o", "--output", default="file_output_is_disabled")
myArgParser.add_argument("-noG", "--exclude-all-3-10-helix", action='store_true')
myArgParser.add_argument("-allG", "--include-all-3-10-helix", action='store_true')
myArgParser.add_argument("-noOther", "--exclude-other-group-from-turn-assignment", action='store_true')
myArgParser.add_argument("-Ca1Ca4", "--Ca1Ca4-distance-cutoff", default=7.0)
myArgParser.add_argument("--quiet", action='store_true')
myArgParser.add_argument("--no-comments", action='store_true')
myArgParser.add_argument("--no-table-format", action='store_true')
myArgParser.add_argument("--no-seq-format", action='store_true')
myArgParser.add_argument("--yes-singleline-format", action='store_true')
myArgParser.add_argument("-mode", "--report-closest-mode-torsions", action='store_true')
myArgParser.add_argument("-medoid", "--report-closest-medoid-torsions", action='store_true')
myArgParser.add_argument("-everything", "--print-any-4-res-segments", action='store_true')
myArgParser.add_argument("--yes-2nd-turn-alternative-for-other-group", action='store_true')
myArgParser.add_argument("--library", default=glob_default_bturn_library_filename)
myArgParser.add_argument("--dssp", default='undefined')
myArgParser.add_argument("-h", "--help", action='store_true')
#actual parsing of input arguments
args = myArgParser.parse_args()
#when no arguments are provided or help flag is provided, the program has to give the full help information and quit
if len(sys.argv) <= 1:
args.help = True
if args.dssp == 'undefined':
if glob_operating_system == 'win':
glob_fPath_dssp_binary = r'dssp_win'
elif glob_operating_system == 'unix':
glob_fPath_dssp_binary = r'dssp_unix'
elif glob_operating_system == 'mac':
glob_fPath_dssp_binary = r'dssp_mac'
else:
glob_fPath_dssp_binary = args.dssp
#compiling full-path filename for DSSP binary, input could be simple filename, relative filename and full path
if os.path.isfile(os.path.join(glob_fpath_script_dir, 'DSSP', glob_fPath_dssp_binary)):
#if the last parameter is full path, path.join function return the last parameter
glob_fPath_dssp_binary = os.path.join(glob_fpath_script_dir, 'DSSP', glob_fPath_dssp_binary)
elif os.path.isfile(os.path.join(os.getcwd(), glob_fPath_dssp_binary)):
glob_fPath_dssp_binary = os.path.join(os.getcwd(), glob_fPath_dssp_binary)
else:
glob_fPath_dssp_binary = glob_fPath_dssp_binary
if args.help or (not args.quiet and not args.no_comments):
PrintProgramInformation()
#if the second parameter is full path, path.join function return the second parameter
glob_fPath_BetaTurnLib = os.path.join(glob_fpath_script_dir, 'BetaTurnLib18', args.library)
#load beta-turn types with their characteristics from included external file
glob_bTurnLibListOfDict = ReadBetaTurnLibrary(glob_fPath_BetaTurnLib, args)
Extend_bTurnLibListOfDict_WithAdditInfo(glob_bTurnLibListOfDict)
if args.help:
print '# '
myArgParser.print_help()
if args.help:
print '# '
PrintProgramUsage()
if args.help or (not args.quiet and not args.no_comments):
Print_bTurns_Information()
Print_bturn_type_confidence_Information()
if args.help or (not args.quiet and not args.no_comments):
print '# '
if args.exclude_other_group_from_turn_assignment:
print "# Other group is exclude from the beta-turn assignment."
print "# The closest turn type to a sample turn is assigned from only 18 types."
print "# If the closest turn is too far way, it is still reported and no Other group is reported."
print "# ========================================================================================"
else:
print "# By default, Other group is included into the beta-turn assignment."
print "# The closest turn type to a sample turn is assigned from 18 types and Other group."
print "# If the closest turn is too far way, Other group is reported."
print "# In such case the sample turn does not fit any of 18 turn types."
print "# ================================================================================="
CA1CA4_beta_turn_distance_cutoff = float(args.Ca1Ca4_distance_cutoff)
if args.help or (not args.quiet and not args.no_comments):
print "# "
print "# CA(1)-CA(4) distance threshold = %6.3f A is enforced in a beta-turn definition" % CA1CA4_beta_turn_distance_cutoff
print "# ==============================================================================="
#process the first model in PDB / CIF file with all its chains
how_to_process_3_helix = 'default_allow_isolated_GGG'
if args.exclude_all_3_10_helix == True:
how_to_process_3_helix = 'exclude_all_G'
if args.include_all_3_10_helix == True:
how_to_process_3_helix = 'include_all_G'
if args.help or (not args.quiet and not args.no_comments):
print "# "
if how_to_process_3_helix == 'default_allow_isolated_GGG':
print "# The default allows the 2nd and 3rd beta-turn residues in an isolated 3-10 helix"
print "# which is not adjacent to an alpha helix (H) on either side."
print "# For example, CGGGC or EGGGE are allowed while HGGGC or CGGGH or CGGGGC are not analyzed for turns."
print "# =================================================================================================="
elif how_to_process_3_helix == 'exclude_all_G':
print "# The optional argument flag %s is enforced" % '--exclude-all-3-10-helix'
print "# The 2nd and 3rd beta-turn residues are restricted in a 3-10 helix of any length."
print "# ========================================================================================"
elif how_to_process_3_helix == 'include_all_G':
print "# The optional argument flag %s is enforced" % '--include-all-3-10-helix'
print "# The 2nd and 3rd beta-turn residues are allowed in a 3-10 helix of any length."
print "# ====================================================================================="
if args.help:
#quiting since no arguments provided
return
#post arg parsing processing
if args.exclude_all_3_10_helix == True and args.include_all_3_10_helix == True:
raise Exception('Argument error: --exclude-all-3-10-helix and --include-all-3-10-helix are not allowed at the same time')
if args.input == None:
print('Argument error: An input protein structure is required specified with -i or --input')
return
#as precautionary step not to use this threshold by a mistake
if args.exclude_other_group_from_turn_assignment:
del glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other
fileNameStructure = args.input
outputFilename = args.output
#-----------------------
#all arguments processed
if not args.quiet and not args.no_comments:
print "# "
_tempString = "Input filename = %s" % (fileNameStructure)
print "# %s" % _tempString
print '# ' + '*' * len(_tempString)
del _tempString
if not args.quiet and not args.no_comments and not args.no_table_format:
print "# "
print "# Detected beta turns in a table format:"
print "# --------------------------------------"
if outputFilename not in ('file_output_is_disabled', None):
outputfile = open(outputFilename, 'wt')
else:
outputfile = None
ProcessOneModelWithAllChains(fileNameStructure, outputfile, how_to_process_3_helix, args)
if outputfile != None:
outputfile.close()
def ReadBetaTurnLibrary(_fPathBTurnClusterMedoidsFile, _args):
global glob_BetaTurnLib_version;
_bTurnLibListOfDict = []
with open(_fPathBTurnClusterMedoidsFile, 'rt') as csvfile:
cvsreader = csv.DictReader(csvfile, delimiter='\t', fieldnames=['no_by_size', 'cluster_size', 'frequency', 'bturn_name', 'prev_name', 'median_below_7A_ca1_ca4', 'mean_below_7A_ca1_ca4', 'median_any_ca1_ca4', 'mean_any_ca1_ca4', 'mode_omega2', 'mode_phi2', 'mode_psi2', 'mode_omega3', 'mode_phi3', 'mode_psi3', 'mode_omega4', 'mode_aa1', 'mode_aa2', 'mode_aa3', 'mode_aa4', 'mode_ss1', 'mode_ss2', 'mode_ss3', 'mode_ss4', 'mode_pdb_id', 'mode_chain_id', 'mode_res1_id', 'medoid_omega2', 'medoid_phi2', 'medoid_psi2', 'medoid_omega3', 'medoid_phi3', 'medoid_psi3', 'medoid_omega4', 'medoid_aa1', 'medoid_aa2', 'medoid_aa3', 'medoid_aa4', 'medoid_ss1', 'medoid_ss2', 'medoid_ss3', 'medoid_ss4', 'medoid_pdb_id', 'medoid_chain_id', 'medoid_res1_id'])
for row in cvsreader:
if row['no_by_size'][0] == '#' or row['no_by_size'] == 'no_by_size':
if row['no_by_size'][0:10] == '# Version ':
glob_BetaTurnLib_version = row['no_by_size'].split()[2]
continue
elif row['no_by_size'] != 'total':
if _args.exclude_other_group_from_turn_assignment and row['no_by_size'] == 'Other':
continue
_bTurnLibListOfDict.append(row)
return _bTurnLibListOfDict
def ProcessOneModelWithAllChains(_fileNameStructure, _outputfile, _how_to_process_3_helix, _args):
#disabling annoying PDB warnings
warnings.filterwarnings("ignore", message = '.*Chain .? is discontinuous.*')
warnings.filterwarnings("ignore", message = '.*Could not assign element.*')
warnings.filterwarnings("ignore", message = '.*Residue .? is discontinuous.*')
warnings.filterwarnings("ignore", message = '.*no atoms read before TER record.*')
warnings.filterwarnings("ignore", message = '.*Negative occupancy in one or more atoms.*')
warnings.filterwarnings("ignore", message = '.*Used element.*with given element.*')
warnings.filterwarnings("ignore", message = '.*Residue.*redefined at line.*')
if '.cif' not in os.path.splitext(_fileNameStructure)[1].lower() and '.mmcif' not in os.path.splitext(_fileNameStructure)[1].lower():
pdbParser = Bio.PDB.PDBParser(PERMISSIVE=1)
proteinStruct = pdbParser.get_structure("my_pdb " + _fileNameStructure, _fileNameStructure)
else:
cifParser = Bio.PDB.MMCIFParser()
proteinStruct = cifParser.get_structure("my_cif " + _fileNameStructure, _fileNameStructure)
#take the first model from the input structure file
_proteinModel = proteinStruct[0]
#execute dssp installed on a local computer to assign secondary structure to input protein structure
dssp_class = RunDsspAndStoreResultsInChainDictionary(_proteinModel, _fileNameStructure)
#scan the current model and print all beta turns along with their clusters and ids
ScanInputModelAndAllItsChainsForBetaTurnsAndTheirTypes(_proteinModel, dssp_class, _outputfile, _fileNameStructure, _how_to_process_3_helix, _args)
def RunDsspAndStoreResultsInChainDictionary(_proteinModel, _fileNameStructure):
if '.cif' not in os.path.splitext(_fileNameStructure)[1].lower() and '.mmcif' not in os.path.splitext(_fileNameStructure)[1].lower():
pass
else:
#new PDB file is created on fly from a structure model loaded from a cif file
#it is required in order to run DSSP
if float(Bio.__version__) < 1.72:
import PDBIO_ver_1_72
_pdbio_object = PDBIO_ver_1_72.PDBIO()
else:
_pdbio_object = Bio.PDB.PDBIO()
_pdbio_object.set_structure(_proteinModel)
#save pdb file generated on fly from cif into the current working directory
_fileNameStructure = os.path.join(os.getcwd(), os.path.splitext(os.path.basename(_fileNameStructure))[0] + '_from_cif' + '.pdb')
_pdbio_object.save(_fileNameStructure)
try:
#execute DSSP through biopython, however it requires a binary and runs it on the input PDB file
_dssp_class = Bio.PDB.DSSP(_proteinModel, _fileNameStructure, dssp=glob_fPath_dssp_binary)
except Exception as _exception:
#problem with DSSP binary detected, figure out what is wrong and suggest a fix to the user
print ""
print "***** ERROR *********************************************************"
if os.path.isfile(glob_fPath_dssp_binary):
print "Cannot execute DSSP, \'%s\' in your operating system detected as '%s'." % (glob_fPath_dssp_binary, glob_operating_system_full)
print ""
print "Exact DSSP error message is '" + _exception.message + "'"
print ""
print "This Software relies on DSSP, a secondary structure assignment tool."
print "Please try other DSSP binaries included with this Software:"
print ""
_search_pattern = os.path.join(glob_fpath_script_dir, 'DSSP', 'dssp_' + glob_operating_system + r'*')
import glob
_alternative_dssp_files = glob.glob(_search_pattern)
_count = 0
for __file in _alternative_dssp_files:
_count += 1
print "%d) \'%s\'" % (_count, os.path.split(__file)[1])
print ""
print "You can specify an alternative DSSP filename with an additional argument, for example:"
print "\'python %s --dssp my_dssp_executable ...\'" % __file__
print "or \'python %s --dssp /home/user/tools/BetaTurnTool18/my_dssp_executable ...\'" % __file__
print ""
print "If none of them are compatible with your operating system,"
print "you will need to download or compile your own DSSP to make this Software work."
else:
print "Cannot locate DSSP, \'%s\'." % glob_fPath_dssp_binary
print ""
print "This Software relies on DSSP, a secondary structure assignment tool."
print "Please make sure its path and filename are correct."
print ""
print "You can specify the DSSP filename with an additional argument, for example:"
print "\'python %s --dssp my_dssp_executable ...\'" % __file__
print "or \'python %s --dssp /home/user/tools/BetaTurnTool18/my_dssp_executable ...\'" % __file__
print "********************************************************************"
print ""
exit(1)
return _dssp_class
def ScanInputModelAndAllItsChainsForBetaTurnsAndTheirTypes(_proteinModel, _dssp_class, _outputfile, _fileNameStructure, _how_to_process_3_helix, _args):
#http://biopython.org/DIST/docs/api/Bio.SeqIO.PdbIO-module.html
_dict_of_seqres_by_chain = {}
for record in Bio.SeqIO.parse(_fileNameStructure, "pdb-seqres"):
_dict_of_seqres_by_chain[record.annotations["chain"]] = record.seq._data
_torsionNameDualList = [['omega2','medoid_omega2'], ['phi2', 'medoid_phi2'], ['psi2', 'medoid_psi2'], ['omega3', 'medoid_omega3'], ['phi3', 'medoid_phi3'], ['psi3', 'medoid_psi3'], ['omega4','medoid_omega4']]
_detected_beta_turns_count = 0
one = None
two = None
thr = None
fou = None
for _chain in _proteinModel:
_chain_id = _chain.id
_PDB4_originalcase = (os.path.splitext(os.path.basename(_fileNameStructure))[0])
if not _args.quiet and not _args.no_comments:
print "# "
print "# Structure_name = %s" % (_PDB4_originalcase)
print "# Structure_chain = %s" % (_chain_id)
print "# "
PrintColumnNames(_outputfile, _args)
table_of_bturn_info_strings_as_dict_by_index_of_res1_withcoord = {}
if _chain_id in _dict_of_seqres_by_chain.keys():
fullSeqFromPDBSeqResRecord = _dict_of_seqres_by_chain[_chain_id]
else:
fullSeqFromPDBSeqResRecord = None
seqOnMyOwnWCoords = ''
ssFromDSSPWCoords = ''
#of residue where exactly it is
_wcoordindex = -1
bturns_dict_by_index_of_res1_withcoord = {}
bturn_is_processed_dict_by_index_of_res1_withcoord = {}
for _residue in _chain:
is_standard_20aa = True
if _residue.resname not in ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']:
is_standard_20aa = False
if is_standard_20aa == False:
if Bio.PDB.is_aa(_residue) == False:
continue
if len(_residue.resname.strip()) <= 2:
continue
if _residue.id[0] != ' ':
if len(_residue.child_list) <= 1:
continue
if 'N' not in _residue.child_dict.keys() or 'CA' not in _residue.child_dict.keys() or 'C' not in _residue.child_dict.keys():
continue
#to fight HETATM standard aa after TER (another option OXT atom in the terminal residue)
if is_standard_20aa == True:
if _residue.id[0] != ' ':
continue
#at the end of execution
if fullSeqFromPDBSeqResRecord != None and len(seqOnMyOwnWCoords) + 1 > len(fullSeqFromPDBSeqResRecord):
break
one = two
two = thr
thr = fou
if is_standard_20aa == True:
fou = _residue
seqOnMyOwnWCoords = seqOnMyOwnWCoords + Bio.SeqUtils.IUPACData.protein_letters_3to1[_residue.resname.title()]
_wcoordindex += 1
else:
fou = None
#more generic definition of a residue (ATOM vs HETATM)
if Bio.PDB.is_aa(_residue):
#sometimes it does not detect GDP with HETAM with is_aa method (not reliable)
#08/11/2018 - to process modified residues properly - not to cause shift in SS, we need to continue:
#seqOnMyOwnWCoords = seqOnMyOwnWCoords + '?'
#no continie (before)
seqOnMyOwnWCoords = seqOnMyOwnWCoords + ''
continue
else:
raise Exception('Error: impossible because of the condition few lines above')
if (_chain_id, _residue.id) in _dssp_class:
ssFromDSSPWCoords = ssFromDSSPWCoords + _dssp_class[(_chain_id, _residue.id)][2].replace('-', 'C')
else:
if (_chain_id, (' ', _residue.id[1], ' ')) in _dssp_class:
ssFromDSSPWCoords = ssFromDSSPWCoords + _dssp_class[(_chain_id, (' ', _residue.id[1], ' '))][2].replace('-', 'C')
else:
ssFromDSSPWCoords = ssFromDSSPWCoords + '?'
continue
if one != None and two != None and thr != None and fou != None:
if (_chain_id, one.id) in _dssp_class:
SS1 = _dssp_class[(_chain_id, one.id)][2].replace('-', 'C')
elif (_chain_id, (' ', one.id, ' ')) in _dssp_class:
SS1 = _dssp_class[(_chain_id, (' ', one.id, ' '))][2].replace('-', 'C')
else:
continue
if (_chain_id, two.id) in _dssp_class:
SS2 = _dssp_class[(_chain_id, two.id)][2].replace('-', 'C')
elif (_chain_id, (' ', two.id, ' ')) in _dssp_class:
SS2 = _dssp_class[(_chain_id, (' ', two.id, ' '))][2].replace('-', 'C')
else:
continue
if (_chain_id, thr.id) in _dssp_class:
SS3 = _dssp_class[(_chain_id, thr.id)][2].replace('-', 'C')
elif (_chain_id, (' ', thr.id, ' ')) in _dssp_class:
SS3 = _dssp_class[(_chain_id, (' ', thr.id, ' '))][2].replace('-', 'C')
else:
continue
if (_chain_id, fou.id) in _dssp_class:
SS4 = _dssp_class[(_chain_id, fou.id)][2].replace('-', 'C')
elif (_chain_id, (' ', fou.id, ' ')) in _dssp_class:
SS4 = _dssp_class[(_chain_id, (' ', fou.id, ' '))][2].replace('-', 'C')
else:
continue
#here used to be a condition checking _report_all_residues and SS2/SS3 for E, H, G and I
if _args.print_any_4_res_segments:
pass
else:
#Do not allow E, H or I at SS2 or SS3
#Keep processing of G for later
if SS2 == 'E' or SS2 == 'H' or SS2 == 'I' or \
SS3 == 'E' or SS3 == 'H' or SS3 == 'I':
continue
#checking and defining required atoms
_allReqsMet = True
#used later for alternative confirmations
_1st_atoms_involved = []
_2nd_atoms_involved = []
_3rd_atoms_involved = []
_4th_atoms_involved = []
#one
if 'CA' in one.child_dict.keys():
CA1 = one['CA']
_1st_atoms_involved.append(CA1)
else:
_allReqsMet = False
continue
if 'C' in one.child_dict.keys():
C1 = one['C']
_1st_atoms_involved.append(C1)
else:
_allReqsMet = False
continue
#two
if 'N' in two.child_dict.keys():
N2 = two['N']
_2nd_atoms_involved.append(N2)
else:
_allReqsMet = False
continue
if 'CA' in two.child_dict.keys():
CA2 = two['CA']
_2nd_atoms_involved.append(CA2)
else:
_allReqsMet = False
continue
if 'C' in two.child_dict.keys():
C2 = two['C']
_2nd_atoms_involved.append(C2)
else:
_allReqsMet = False
continue
#thr
if 'N' in thr.child_dict.keys():
N3 = thr['N']
_3rd_atoms_involved.append(N3)
else:
_allReqsMet = False
continue
if 'CA' in thr.child_dict.keys():
CA3 = thr['CA']
_3rd_atoms_involved.append(CA3)
else:
_allReqsMet = False
continue
if 'C' in thr.child_dict.keys():
C3 = thr['C']
_3rd_atoms_involved.append(C3)
else:
_allReqsMet = False
continue
#fou aka four
if 'N' in fou.child_dict.keys():
N4 = fou['N']
_4th_atoms_involved.append(N4)
else:
_allReqsMet = False
continue
if 'CA' in fou.child_dict.keys():
CA4 = fou['CA']
_4th_atoms_involved.append(CA4)
else:
_allReqsMet = False
continue
if _allReqsMet == False:
raise Exception('Error: investigate we should have already continued the loop')
#checking whether to skip quad if one of them is
#disconnected (not bonded with the previous one)
CA1CA2 = CA2 - CA1
CA2CA3 = CA3 - CA2
CA3CA4 = CA4 - CA3
if global_SkipProcessingOfAlternativeConformations == True:
#we enforce stricter requirements when we process single conformations only
if CA1.altloc != C1.altloc:
continue
if N2.altloc != CA2.altloc or CA2.altloc != C2.altloc:
continue
#3 is skipped on purpose
if N4.altloc != CA4.altloc:
continue
else:
#we weaken requirements on alternative conformations when we process them
pass
if CA1CA2 > 4.5:
continue
if CA2CA3 > 4.5:
continue
if CA3CA4 > 4.5:
continue
#figuring out disordered level of thr aka third with regard
#to one, two and fou
one_residue_is_disordered = bool(one.disordered)
two_residue_is_disordered = bool(two.disordered)
thr_residue_is_disordered = bool(thr.disordered)
fou_residue_is_disordered = bool(fou.disordered)
parent_quad_disorder_class = -1
#pay attention it relates to the atoms involved only
#for one, two and fou. They are N and CA and C right now!
if thr_residue_is_disordered == False and (one_residue_is_disordered == False and two_residue_is_disordered == False and fou_residue_is_disordered == False):
parent_quad_disorder_class = 10000
for atom in (_1st_atoms_involved + _2nd_atoms_involved + _4th_atoms_involved):
if atom.occupancy < 1:
parent_quad_disorder_class = 11000
break
for atom in _3rd_atoms_involved:
if atom.occupancy < 1:
parent_quad_disorder_class = 12000
break
elif thr_residue_is_disordered == False and (one_residue_is_disordered == True or two_residue_is_disordered == True or fou_residue_is_disordered == True):
parent_quad_disorder_class = 13000
for atom in _3rd_atoms_involved:
if atom.occupancy < 1:
parent_quad_disorder_class = 13100
break
for atom in (_1st_atoms_involved + _2nd_atoms_involved + _4th_atoms_involved):
if hasattr(atom, 'child_dict'):
if (parent_quad_disorder_class == 13000 or parent_quad_disorder_class == 13100) and (atom.id == 'N' or atom.id == 'CA' or atom.id == 'C' or atom.id == 'O'):
parent_quad_disorder_class += 10
break
elif thr_residue_is_disordered == True and (one_residue_is_disordered == False and two_residue_is_disordered == False and fou_residue_is_disordered == False):
parent_quad_disorder_class = 20000
for atom in (_1st_atoms_involved + _2nd_atoms_involved + _4th_atoms_involved):
if atom.occupancy < 1:
parent_quad_disorder_class = 21000
break
elif thr_residue_is_disordered == True and (one_residue_is_disordered == True or two_residue_is_disordered == True or fou_residue_is_disordered == True):
parent_quad_disorder_class = 30000
else:
raise Exception('Error: it must not happen -- please investigate')
_altLoop_3rd = []
if parent_quad_disorder_class >= 10000 and parent_quad_disorder_class < 20000:
#even when there are alternative confirmation -- still
#take the main one (1.3 or 1.31) for neighbors
_altLoop_3rd = [' ']
elif parent_quad_disorder_class >= 20000 and parent_quad_disorder_class < 30000:
#there are no disordered confirmations for neigbors at
#all -- clean
_altLoop_3rd = []
for atom in _3rd_atoms_involved:
if hasattr(atom, 'child_dict'):
if (parent_quad_disorder_class == 20000 or parent_quad_disorder_class == 21000) and (atom.id == 'N' or atom.id == 'CA' or atom.id == 'C' or atom.id == 'O'):
parent_quad_disorder_class += 100
_altLoop_3rd = _altLoop_3rd + atom.child_dict.keys()
_altLoop_3rd = list(set(_altLoop_3rd))
elif parent_quad_disorder_class >= 30000 and parent_quad_disorder_class < 40000:
#we demand main confirmation on neighbors -- do no try
#other combinations
_altLoop_3rd = []
for atom in _3rd_atoms_involved:
if hasattr(atom, 'child_dict'):
if parent_quad_disorder_class == 30000 and (atom.id == 'N' or atom.id == 'CA' or atom.id == 'C' or atom.id == 'O'):
parent_quad_disorder_class += 100
_altLoop_3rd = _altLoop_3rd + atom.child_dict.keys()
_altLoop_3rd = list(set(_altLoop_3rd))
for atom in (_1st_atoms_involved + _2nd_atoms_involved + _4th_atoms_involved):
if hasattr(atom, 'child_dict'):
if (parent_quad_disorder_class == 30000 or parent_quad_disorder_class == 30100) and (atom.id == 'N' or atom.id == 'CA' or atom.id == 'C' or atom.id == 'O'):
parent_quad_disorder_class += 10
break
if parent_quad_disorder_class < 0:
raise Exception('Error: parent_quad_disorder_class had to be defined already')
if global_SkipProcessingOfAlternativeConformations == False:
#to enforce only the main conformation for third residue and main conformations for first, second and forth (no matter single-conformational or multiple-conformational)
_altLoop_3rd = [' ']
#atoms for neighbors stay the same -- we already pulled
#the main ones
for _alt_3rd in _altLoop_3rd:
quad_disorder_class = parent_quad_disorder_class
if _alt_3rd != ' ':
_altConfForAll3rdAtomsFound = True
if thr['N'].disordered_flag == 1:
if _alt_3rd in thr['N'].child_dict.keys():
N3 = thr['N'].child_dict[_alt_3rd]
else:
N3 = thr['N']
_altConfForAll3rdAtomsFound = False
else:
N3 = thr['N']
_altConfForAll3rdAtomsFound = False
if thr['CA'].disordered_flag == 1:
if _alt_3rd in thr['CA'].child_dict.keys():
CA3 = thr['CA'].child_dict[_alt_3rd]
else:
CA3 = thr['CA']
_altConfForAll3rdAtomsFound = False
else:
CA3 = thr['CA']
_altConfForAll3rdAtomsFound = False
if thr['C'].disordered_flag == 1:
if _alt_3rd in thr['C'].child_dict.keys():
C3 = thr['C'].child_dict[_alt_3rd]
else:
C3 = thr['C']
_altConfForAll3rdAtomsFound = False
else:
C3 = thr['C']
_altConfForAll3rdAtomsFound = False
if _altConfForAll3rdAtomsFound == False:
quad_disorder_class += 1
#need to recalculate
CA1CA2 = CA2 - CA1
CA2CA3 = CA3 - CA2
CA3CA4 = CA4 - CA3
if CA1CA2 > 4.5:
continue
if CA2CA3 > 4.5:
continue
if CA3CA4 > 4.5:
continue
#end of if _alt_3rd != ' ':
#distance
CA1CA4 = CA4 - CA1
#_wcoordindex - 3 corresponds to the first residue of a beta turn
bturn_is_processed_dict_by_index_of_res1_withcoord[_wcoordindex - 3] = True
if _args.print_any_4_res_segments:
pass
else:
if CA1CA4 > CA1CA4_beta_turn_distance_cutoff:
continue
if global_SkipProcessingOfAlternativeConformations == True:
if quad_disorder_class != 10000:
continue
else:
#do not demand single-conformational and 1.0 at 1st, 2nd, 3rd and 4th residues any longer (03/23/2018)
pass
#defining required atom vectors
#one aka 1
CA1vec = CA1.get_vector()
C1vec = C1.get_vector()
#two aka 2
N2vec = N2.get_vector()
CA2vec = CA2.get_vector()
C2vec = C2.get_vector()
#three aka 3
N3vec = N3.get_vector()
CA3vec = CA3.get_vector()
C3vec = C3.get_vector()
#fou aka 4
N4vec = N4.get_vector()
CA4vec = CA4.get_vector()
#backbone torsion angles for 1 thru 4:
#one
#psi1 = Bio.PDB.calc_dihedral(N1vec, CA1vec, C1vec, N2vec)
#two
omega2 = Bio.PDB.calc_dihedral(CA1vec, C1vec, N2vec, CA2vec)
phi2 = Bio.PDB.calc_dihedral(C1vec, N2vec, CA2vec, C2vec)
psi2 = Bio.PDB.calc_dihedral(N2vec, CA2vec, C2vec, N3vec)
#thr aka 3
omega3 = Bio.PDB.calc_dihedral(CA2vec, C2vec, N3vec, CA3vec)
phi3 = Bio.PDB.calc_dihedral(C2vec, N3vec, CA3vec, C3vec)
psi3 = Bio.PDB.calc_dihedral(N3vec, CA3vec, C3vec, N4vec)
#fou aka 4
omega4 = Bio.PDB.calc_dihedral(CA3vec, C3vec, N4vec, CA4vec)
#phi4 = Bio.PDB.calc_dihedral(C3vec, N4vec, CA4vec, C4vec)
aa1 = Bio.SeqUtils.IUPACData.protein_letters_3to1[one.resname.title()]
aa2 = Bio.SeqUtils.IUPACData.protein_letters_3to1[two.resname.title()]
aa3 = Bio.SeqUtils.IUPACData.protein_letters_3to1[thr.resname.title()]
aa4 = Bio.SeqUtils.IUPACData.protein_letters_3to1[fou.resname.title()]
#find closest beta-turn cluster and report all information for the current beta turn
_L1_2Cos_Aver_array = numpy.zeros(len(glob_bTurnLibListOfDict)-1)
for j in range(len(glob_bTurnLibListOfDict)-1):
for _torsionNamePair in _torsionNameDualList:
_L1_2Cos_Aver_array[j] += 2 * (1 - numpy.cos(locals()[_torsionNamePair[0]] - numpy.radians(float(glob_bTurnLibListOfDict[j][_torsionNamePair[1]]))))
_L1_2Cos_Aver_array[j] /= len(_torsionNameDualList)
_closest_cluster_index = numpy.argmin(_L1_2Cos_Aver_array)
_distance_to_closest_cluster_native = _L1_2Cos_Aver_array[_closest_cluster_index]
#d2 = 2 * (1 - numpy.cos(numpy.radians(realDeg)))
#realDeg = numpy.degrees(numpy.arccos(1 - d2 / 2.))
_distance_to_closest_cluster_degree = numpy.degrees(numpy.arccos(1 - _distance_to_closest_cluster_native / 2.))
_L1_2Cos_Aver_array[_closest_cluster_index] = 999999.
_2nd_closest_cluster_index = numpy.argmin(_L1_2Cos_Aver_array)
_distance_to_2nd_closest_cluster_native = _L1_2Cos_Aver_array[_2nd_closest_cluster_index]
_distance_to_2nd_closest_cluster_degree = numpy.degrees(numpy.arccos(1 - _distance_to_2nd_closest_cluster_native / 2.))
del _L1_2Cos_Aver_array
#case (1)
_confidence_in_closest_type = (1 - _distance_to_closest_cluster_degree / (_distance_to_closest_cluster_degree + _distance_to_2nd_closest_cluster_degree))
_confidence_in_2nd_closest_type = (1 - _distance_to_2nd_closest_cluster_degree / (_distance_to_closest_cluster_degree + _distance_to_2nd_closest_cluster_degree))
if not _args.exclude_other_group_from_turn_assignment:
if not _args.yes_2nd_turn_alternative_for_other_group:
if _distance_to_closest_cluster_native > glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
#case (3)
#When 1st_closest is above the threshold, both 1st and 2nd closest must be above the thresold
if _distance_to_2nd_closest_cluster_native <= glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
raise('Error: impossible that the 2nd closest is not above threshold while the 1st one is above');
#we assign the 1st closest type to Other
_closest_cluster_index = len(glob_bTurnLibListOfDict)-1
#the distance to Other (1st) does not have a defintion, so 999 with positive value, to make it large
_distance_to_closest_cluster_native = 999
_distance_to_closest_cluster_degree = 999
_confidence_in_closest_type = 1.0
#we assign the 2nd closest type to Other as well
_2nd_closest_cluster_index = len(glob_bTurnLibListOfDict)-1
#the distance to Other (1st) does not have a defintion, so 999 with positive value, to make it large
_distance_to_2nd_closest_cluster_native = 999
_distance_to_2nd_closest_cluster_degree = 999
_confidence_in_2nd_closest_type = 0.0
elif _distance_to_2nd_closest_cluster_native > glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
#case (2)
#When the 1st stays with one of 18 types and does NOT become Other,
#however the 2nd above the threshold and becomes Other
#This is because being close enough to one turn and not remotely close to another turn, means our confidence in C1 should be 1.0
_confidence_in_closest_type = 1.0
_2nd_closest_cluster_index = len(glob_bTurnLibListOfDict)-1
#the distance to Other (2nd) does not have a defintion, so 999 with positive value, to make it large
_distance_to_2nd_closest_cluster_native = 999
_distance_to_2nd_closest_cluster_degree = 999
_confidence_in_2nd_closest_type = 0.0
else:
if _distance_to_closest_cluster_native > glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
#case (3)
#When 1st_closest is above the threshold, both 1st and 2nd closest must be above the thresold
if _distance_to_2nd_closest_cluster_native <= glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
raise('Error: impossible that the 2nd closest is not above threshold while the 1st one is above');
#we turn the 1st closest type into the 2nd one
_2nd_closest_cluster_index = _closest_cluster_index
_distance_to_2nd_closest_cluster_native = _distance_to_closest_cluster_native
_distance_to_2nd_closest_cluster_degree = _distance_to_closest_cluster_degree
#we assign the 1st closest type to Other
_closest_cluster_index = len(glob_bTurnLibListOfDict)-1
#the distance to Other (1st) does not have a defintion, so 999 with positive value, to make it large
_distance_to_closest_cluster_native = 999
_distance_to_closest_cluster_degree = 999
#We set Other (1st) with confidence of 0.5 at the border and the rest goes to the original 1st (now 2nd)
#Pay attention that _distance_to_2nd_closest_cluster_native now holds the original 1st closest _distance_to_closest_cluster_native
#after reassignment
_confidence_in_2nd_closest_type = 1 - 0.5 * _distance_to_2nd_closest_cluster_native/glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other
#It is possible that the original closest cluster (now 2nd choice) is too far away from the border.
#More exactly twice the distance threshold. We cannot allow negative confidence or probability,
#so we set it to 0.0
if _confidence_in_2nd_closest_type < 0:
_confidence_in_2nd_closest_type = 0.0
_confidence_in_closest_type = 1 - _confidence_in_2nd_closest_type
elif _distance_to_2nd_closest_cluster_native > glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other:
#case (2)
#When the 1st stays with one of 18 types and does NOT become Other,
#however the 2nd above the threshold and becomes Other
_2nd_closest_cluster_index = len(glob_bTurnLibListOfDict)-1
#the distance to Other (2nd) does not have a defintion, so 999 with positive value, to make it large
_distance_to_2nd_closest_cluster_native = 999
_distance_to_2nd_closest_cluster_degree = 999
#_confidence_in_closest_type cannot become negative because with this 2nd condition,
#_distance_to_closest_cluster_native is already satisfied to be below the threshold
_confidence_in_closest_type = 1 - 0.5 * _distance_to_closest_cluster_native/glob_max_L1Distance_betw_closestMedoid_sample_otherwise_Other