-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTMalign.cpp
More file actions
5137 lines (4671 loc) · 178 KB
/
TMalign.cpp
File metadata and controls
5137 lines (4671 loc) · 178 KB
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
/* TM-align: sequence-independent structure alignment of monomer proteins by
* TM-score superposition. Please report issues to yangzhanglab@umich.edu
*
* References to cite:
* Y Zhang, J Skolnick. Nucl Acids Res 33, 2302-9 (2005)
*
* DISCLAIMER:
* Permission to use, copy, modify, and distribute the Software for any
* purpose, with or without fee, is hereby granted, provided that the
* notices on the head, the reference information, and this copyright
* notice appear in all copies or substantial portions of the Software.
* It is provided "as is" without express or implied warranty.
*
* ==========================
* How to install the program
* ==========================
* The following command compiles the program in your Linux computer:
*
* g++ -static -O3 -ffast-math -lm -o TMalign TMalign.cpp
*
* The '-static' flag should be removed on Mac OS, which does not support
* building static executables.
*
* ======================
* How to use the program
* ======================
* You can run the program without argument to obtain the document.
* Briefly, you can compare two structures by:
*
* ./TMalign structure1.pdb structure2.pdb
*
* ==============
* Update history
* ==============
* 2012/01/24: A C/C++ code of TM-align was constructed by Jianyi Yang
* 2016/05/21: Several updates of this program were made by Jianji Wu:
* (1) fixed several compiling bugs
* (2) made I/O of C/C++ version consistent with the Fortran version
* (3) added outputs including full-atom and ligand structures
* (4) added options of '-i', '-I' and '-m'
* 2016/05/25: Fixed a bug on PDB file reading
* 2018/06/04: Several updates were made by Chengxin Zhang, including
* (1) Fixed bug in reading PDB files with negative residue index,
* (2) Implemented the fTM-align algorithm (by the '-fast' option)
* as described in R Dong, S Pan, Z Peng, Y Zhang, J Yang
* (2018) Nucleic acids research. gky430.
* (3) Included option to perform TM-align against a whole
* folder of PDB files. A full list of options not available
* in the Fortran version can be explored by TMalign -h
* 2018/07/27: Added the -byresi option for TM-score superposition without
* re-alignment as in TMscore and TMscore -c
* 2018/08/07: Added the -dir option
* 2018/08/14: Added the -split option
* 2018/08/16: Added the -infmt1, -infmt2 options.
* 2019/01/07: Added support for PDBx/mmCIF format.
* 2019/02/09: Fixed asymmetric alignment bug.
* 2019/03/17: Added the -cp option for circular permutation
* 2019/07/23: Supported RasMol output by '-o' option
* 2019/07/24: Fixed bug on PyMOL format output by '-o' option with mmCIF input
* 2019/08/18: Fixed bug on RasMol format output file *_atm. Removed excessive
* circular permutation alignment by -cp
* 2019/08/20: Clarified PyMOL syntax.
* 2019/08/22: Added four additional PyMOL scripts.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <malloc.h>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
void print_version()
{
cout <<
"\n"
" *********************************************************************\n"
" * TM-align (Version 20190822): protein structure alignment *\n"
" * References: Y Zhang, J Skolnick. Nucl Acids Res 33, 2302-9 (2005) *\n"
" * Please email comments and suggestions to yangzhanglab@umich.edu *\n"
" *********************************************************************"
<< endl;
}
void print_extra_help()
{
cout <<
"Additional options:\n"
" -dir Perform all-against-all alignment among the list of PDB\n"
" chains listed by 'chain_list' under 'chain_folder'. Note\n"
" that the slash is necessary.\n"
" $ TMalign -dir chain_folder/ chain_list\n"
"\n"
" -dir1 Use chain2 to search a list of PDB chains listed by 'chain1_list'\n"
" under 'chain1_folder'. Note that the slash is necessary.\n"
" $ TMalign -dir1 chain1_folder/ chain1_list chain2\n"
"\n"
" -dir2 Use chain1 to search a list of PDB chains listed by 'chain2_list'\n"
" under 'chain2_folder'\n"
" $ TMalign chain1 -dir2 chain2_folder/ chain2_list\n"
"\n"
" -suffix (Only when -dir1 and/or -dir2 are set, default is empty)\n"
" add file name suffix to files listed by chain1_list or chain2_list\n"
"\n"
" -atom 4-character atom name used to represent a residue.\n"
" Default is \" CA \" for proteins\n"
" (note the spaces before and after CA).\n"
"\n"
" -ter Strings to mark the end of a chain\n"
" 3: (default) TER, ENDMDL, END or different chain ID\n"
" 2: ENDMDL, END, or different chain ID\n"
" 1: ENDMDL or END\n"
" 0: (default in the first C++ TMalign) end of file\n"
"\n"
" -split Whether to split PDB file into multiple chains\n"
" 0: (default) treat the whole structure as one single chain\n"
" 1: treat each MODEL as a separate chain (-ter should be 0)\n"
" 2: treat each chain as a seperate chain (-ter should be <=1)\n"
"\n"
" -outfmt Output format\n"
" 0: (default) full output\n"
" 1: fasta format compact output\n"
" 2: tabular format very compact output\n"
" -1: full output, but without version or citation information\n"
"\n"
" -byresi Whether to assume residue index correspondence between the\n"
" two structures.\n"
" 0: (default) sequence independent alignment\n"
" 1: (same as TMscore program) sequence-dependent superposition,\n"
" i.e. align by residue index\n"
" 2: (same as TMscore -c, should be used with -ter <=1)\n"
" align by residue index and chain ID\n"
" 3: (similar to TMscore -c, should be used with -ter <=1)\n"
" align by residue index and order of chain\n"
"\n"
" -TMcut -1: (default) do not consider TMcut\n"
" Values in [0.5,1): Do not proceed with TM-align for this\n"
" structure pair if TM-score is unlikely to reach TMcut.\n"
" TMcut is normalized is set by -a option:\n"
" -2: normalized by longer structure length\n"
" -1: normalized by shorter structure length\n"
" 0: (default, same as F) normalized by second structure\n"
" 1: same as T, normalized by average structure length\n"
"\n"
" -mirror Whether to align the mirror image of input structure\n"
" 0: (default) do not align mirrored structure\n"
" 1: align mirror of chain1 to origin chain2\n"
"\n"
" -het Whether to align residues marked as 'HETATM' in addition to 'ATOM '\n"
" 0: (default) only align 'ATOM ' residues\n"
" 1: align both 'ATOM ' and 'HETATM' residues\n"
"\n"
" -infmt1 Input format for chain1\n"
" -infmt2 Input format for chain2\n"
" -1: (default) automatically detect PDB or PDBx/mmCIF format\n"
" 0: PDB format\n"
" 1: SPICKER format\n"
" 2: xyz format\n"
" 3: PDBx/mmCIF format\n"
<<endl;
}
void print_help(bool h_opt=false)
{
print_version();
cout <<
"\n"
"Usage: TMalign PDB1.pdb PDB2.pdb [Options]\n"
"\n"
"Options:\n"
" -u TM-score normalized by user assigned length (the same as -L)\n"
" warning: it should be >= minimum length of the two structures\n"
" otherwise, TM-score may be >1\n"
"\n"
" -a TM-score normalized by the average length of two structures\n"
" T or F, (default F)\n"
"\n"
" -i Start with an alignment specified in fasta file 'align.txt'\n"
"\n"
" -I Stick to the alignment specified in 'align.txt'\n"
"\n"
" -m Output TM-align rotation matrix\n"
"\n"
" -d TM-score scaled by an assigned d0, e.g. 5 Angstroms\n"
"\n"
" -o Output the superposition to 'TM_sup*'\n"
" $ TMalign PDB1.pdb PDB2.pdb -o TM_sup\n"
" View superposed C-alpha traces of aligned regions by RasMol or PyMOL:\n"
" $ rasmol -script TM_sup\n"
" $ pymol -d @TM_sup.pml\n"
" View superposed C-alpha traces of all regions:\n"
" $ rasmol -script TM_sup_all\n"
" $ pymol -d @TM_sup_all.pml\n"
" View superposed full-atom structures of aligned regions:\n"
" $ rasmol -script TM_sup_atm\n"
" $ pymol -d @TM_sup_atm.pml\n"
" View superposed full-atom structures of all regions:\n"
" $ rasmol -script TM_sup_all_atm\n"
" $ pymol -d @TM_sup_all_atm.pml\n"
" View superposed full-atom structures and ligands of all regions\n"
" $ rasmol -script TM_sup_all_atm_lig\n"
" $ pymol -d @TM_sup_all_atm_lig.pml\n"
"\n"
" -fast Fast but slightly inaccurate alignment by fTM-align algorithm\n"
"\n"
" -cp Alignment with circular permutation\n"
"\n"
" -v Print the version of TM-align\n"
"\n"
" -h Print the full help message, including additional options\n"
"\n"
" (Options -u, -a, -d, -o will not change the final structure alignment)\n\n"
"Example usages:\n"
" TMalign PDB1.pdb PDB2.pdb\n"
" TMalign PDB1.pdb PDB2.pdb -u 100 -d 5.0\n"
" TMalign PDB1.pdb PDB2.pdb -a T -o PDB1.sup\n"
" TMalign PDB1.pdb PDB2.pdb -i align.txt\n"
" TMalign PDB1.pdb PDB2.pdb -m matrix.txt\n"
" TMalign PDB1.pdb PDB2.pdb -fast\n"
" TMalign PDB1.pdb PDB2.pdb -cp\n"
<<endl;
if (h_opt) print_extra_help();
exit(EXIT_SUCCESS);
}
/* Functions for the core TMalign algorithm, including the entry function
* TMalign_main */
void PrintErrorAndQuit(const string sErrorString)
{
cout << sErrorString << endl;
exit(1);
}
template <typename T> inline T getmin(const T &a, const T &b)
{
return b<a?b:a;
}
template <class A> void NewArray(A *** array, int Narray1, int Narray2)
{
*array=new A* [Narray1];
for(int i=0; i<Narray1; i++) *(*array+i)=new A [Narray2];
}
template <class A> void DeleteArray(A *** array, int Narray)
{
for(int i=0; i<Narray; i++)
if(*(*array+i)) delete [] *(*array+i);
if(Narray) delete [] (*array);
(*array)=NULL;
}
string AAmap(char A)
{
if (A=='A') return "ALA";
if (A=='B') return "ASX";
if (A=='C') return "CYS";
if (A=='D') return "ASP";
if (A=='E') return "GLU";
if (A=='F') return "PHE";
if (A=='G') return "GLY";
if (A=='H') return "HIS";
if (A=='I') return "ILE";
if (A=='K') return "LYS";
if (A=='L') return "LEU";
if (A=='M') return "MET";
if (A=='N') return "ASN";
if (A=='O') return "PYL";
if (A=='P') return "PRO";
if (A=='Q') return "GLN";
if (A=='R') return "ARG";
if (A=='S') return "SER";
if (A=='T') return "THR";
if (A=='U') return "SEC";
if (A=='V') return "VAL";
if (A=='W') return "TRP";
if (A=='Y') return "TYR";
if (A=='Z') return "GLX";
return "UNK";
}
char AAmap(const string &AA)
{
if (AA.compare("ALA")==0 || AA.compare("DAL")==0) return 'A';
if (AA.compare("ASX")==0) return 'B';
if (AA.compare("CYS")==0 || AA.compare("DCY")==0) return 'C';
if (AA.compare("ASP")==0 || AA.compare("DAS")==0) return 'D';
if (AA.compare("GLU")==0 || AA.compare("DGL")==0) return 'E';
if (AA.compare("PHE")==0 || AA.compare("DPN")==0) return 'F';
if (AA.compare("GLY")==0) return 'G';
if (AA.compare("HIS")==0 || AA.compare("DHI")==0) return 'H';
if (AA.compare("ILE")==0 || AA.compare("DIL")==0) return 'I';
if (AA.compare("LYS")==0 || AA.compare("DLY")==0) return 'K';
if (AA.compare("LEU")==0 || AA.compare("DLE")==0) return 'L';
if (AA.compare("MET")==0 || AA.compare("MED")==0 ||
AA.compare("MSE")==0) return 'M';
if (AA.compare("ASN")==0 || AA.compare("DSG")==0) return 'N';
if (AA.compare("PYL")==0) return 'O';
if (AA.compare("PRO")==0 || AA.compare("DPR")==0) return 'P';
if (AA.compare("GLN")==0 || AA.compare("DGN")==0) return 'Q';
if (AA.compare("ARG")==0 || AA.compare("DAR")==0) return 'R';
if (AA.compare("SER")==0 || AA.compare("DSN")==0) return 'S';
if (AA.compare("THR")==0 || AA.compare("DTH")==0) return 'T';
if (AA.compare("SEC")==0) return 'U';
if (AA.compare("VAL")==0 || AA.compare("DVA")==0) return 'V';
if (AA.compare("TRP")==0 || AA.compare("DTR")==0) return 'W';
if (AA.compare("TYR")==0 || AA.compare("DTY")==0) return 'Y';
if (AA.compare("GLX")==0) return 'Z';
return 'X';
}
/* split a long string into vectors by whitespace
* line - input string
* line_vec - output vector
* delimiter - delimiter */
void split(const string &line, vector<string> &line_vec,
const char delimiter=' ')
{
bool within_word = false;
for (int pos=0;pos<line.size();pos++)
{
if (line[pos]==delimiter)
{
within_word = false;
continue;
}
if (!within_word)
{
within_word = true;
line_vec.push_back("");
}
line_vec.back()+=line[pos];
}
}
/* split a long string into vectors by whitespace, return both whitespaces
* and non-whitespaces
* line - input string
* line_vec - output vector
* space_vec - output vector
* delimiter - delimiter */
void split_white(const string &line, vector<string> &line_vec,
vector<string>&white_vec, const char delimiter=' ')
{
bool within_word = false;
for (int pos=0;pos<line.size();pos++)
{
if (line[pos]==delimiter)
{
if (within_word==true)
{
white_vec.push_back("");
within_word = false;
}
white_vec.back()+=delimiter;
}
else
{
if (within_word==false)
{
line_vec.push_back("");
within_word = true;
}
line_vec.back()+=line[pos];
}
}
}
size_t get_PDB_lines(const string filename,
vector<vector<string> >&PDB_lines, vector<string> &chainID_list,
vector<int> &mol_vec, const int ter_opt, const int infmt_opt,
const string atom_opt, const int split_opt, const int het_opt)
{
size_t i=0; // resi i.e. atom index
string line;
char chainID=0;
string resi="";
bool select_atom=false;
size_t model_idx=0;
vector<string> tmp_str_vec;
ifstream fin;
fin.open(filename.c_str());
if (infmt_opt==0||infmt_opt==-1) // PDB format
{
while (fin.good())
{
getline(fin, line);
if (infmt_opt==-1 && line.compare(0,5,"loop_")==0) // PDBx/mmCIF
return get_PDB_lines(filename,PDB_lines,chainID_list,
mol_vec, ter_opt, 3, atom_opt, split_opt,het_opt);
if (i > 0)
{
if (ter_opt>=1 && line.compare(0,3,"END")==0) break;
else if (ter_opt>=3 && line.compare(0,3,"TER")==0) break;
}
if (split_opt && line.compare(0,3,"END")==0) chainID=0;
if ((line.compare(0, 6, "ATOM ")==0 ||
(line.compare(0, 6, "HETATM")==0 && het_opt))
&& line.size()>=54 && (line[16]==' ' || line[16]=='A'))
{
if (atom_opt=="auto")
select_atom=(line.compare(12,4," CA ")==0);
else select_atom=(line.compare(12,4,atom_opt)==0);
if (select_atom)
{
if (!chainID)
{
chainID=line[21];
model_idx++;
stringstream i8_stream;
i=0;
if (split_opt==2) // split by chain
{
if (chainID==' ')
{
if (ter_opt>=1) i8_stream << ":_";
else i8_stream<<':'<<model_idx<<":_";
}
else
{
if (ter_opt>=1) i8_stream << ':' << chainID;
else i8_stream<<':'<<model_idx<<':'<<chainID;
}
chainID_list.push_back(i8_stream.str());
}
else if (split_opt==1) // split by model
{
i8_stream << ':' << model_idx;
chainID_list.push_back(i8_stream.str());
}
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
}
else if (ter_opt>=2 && chainID!=line[21]) break;
if (split_opt==2 && chainID!=line[21])
{
chainID=line[21];
i=0;
stringstream i8_stream;
if (chainID==' ')
{
if (ter_opt>=1) i8_stream << ":_";
else i8_stream<<':'<<model_idx<<":_";
}
else
{
if (ter_opt>=1) i8_stream << ':' << chainID;
else i8_stream<<':'<<model_idx<<':'<<chainID;
}
chainID_list.push_back(i8_stream.str());
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
}
if (resi==line.substr(22,5))
cerr<<"Warning! Duplicated residue "<<resi<<endl;
resi=line.substr(22,5); // including insertion code
PDB_lines.back().push_back(line);
if (line[17]==' ' && (line[18]=='D'||line[18]==' ')) mol_vec.back()++;
else mol_vec.back()--;
i++;
}
}
}
}
else if (infmt_opt==1) // SPICKER format
{
int L=0;
float x,y,z;
stringstream i8_stream;
while (fin.good())
{
fin >>L>>x>>y>>z;
getline(fin, line);
if (!fin.good()) break;
model_idx++;
stringstream i8_stream;
i8_stream << ':' << model_idx;
chainID_list.push_back(i8_stream.str());
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
for (i=0;i<L;i++)
{
fin >>x>>y>>z;
i8_stream<<"ATOM "<<setw(4)<<i+1<<" CA UNK "<<setw(4)
<<i+1<<" "<<setiosflags(ios::fixed)<<setprecision(3)
<<setw(8)<<x<<setw(8)<<y<<setw(8)<<z;
line=i8_stream.str();
i8_stream.str(string());
PDB_lines.back().push_back(line);
}
getline(fin, line);
}
}
else if (infmt_opt==2) // xyz format
{
int L=0;
char A;
stringstream i8_stream;
while (fin.good())
{
getline(fin, line);
L=atoi(line.c_str());
getline(fin, line);
for (i=0;i<line.size();i++)
if (line[i]==' '||line[i]=='\t') break;
if (!fin.good()) break;
chainID_list.push_back(':'+line.substr(0,i));
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
for (i=0;i<L;i++)
{
getline(fin, line);
i8_stream<<"ATOM "<<setw(4)<<i+1<<" CA "
<<AAmap(line[0])<<" "<<setw(4)<<i+1<<" "
<<line.substr(2,8)<<line.substr(11,8)<<line.substr(20,8);
line=i8_stream.str();
i8_stream.str(string());
PDB_lines.back().push_back(line);
if (line[0]>='a' && line[0]<='z') mol_vec.back()++; // RNA
else mol_vec.back()--;
}
}
}
else if (infmt_opt==3) // PDBx/mmCIF format
{
bool loop_ = false; // not reading following content
map<string,int> _atom_site;
int atom_site_pos;
vector<string> line_vec;
string alt_id="."; // alternative location indicator
string asym_id="."; // this is similar to chainID, except that
// chainID is char while asym_id is a string
// with possibly multiple char
string prev_asym_id="";
string AA=""; // residue name
string atom="";
string prev_resi="";
string model_index=""; // the same as model_idx but type is string
stringstream i8_stream;
while (fin.good())
{
getline(fin, line);
if (line.size()==0) continue;
if (loop_) loop_ = line.compare(0,2,"# ");
if (!loop_)
{
if (line.compare(0,5,"loop_")) continue;
while(1)
{
if (fin.good()) getline(fin, line);
else PrintErrorAndQuit("ERROR! Unexpected end of "+filename);
if (line.size()) break;
}
if (line.compare(0,11,"_atom_site.")) continue;
loop_=true;
_atom_site.clear();
atom_site_pos=0;
_atom_site[line.substr(11,line.size()-12)]=atom_site_pos;
while(1)
{
if (fin.good()) getline(fin, line);
else PrintErrorAndQuit("ERROR! Unexpected end of "+filename);
if (line.size()==0) continue;
if (line.compare(0,11,"_atom_site.")) break;
_atom_site[line.substr(11,line.size()-12)]=++atom_site_pos;
}
if (_atom_site.count("group_PDB")*
_atom_site.count("label_atom_id")*
_atom_site.count("label_comp_id")*
(_atom_site.count("auth_asym_id")+
_atom_site.count("label_asym_id"))*
(_atom_site.count("auth_seq_id")+
_atom_site.count("label_seq_id"))*
_atom_site.count("Cartn_x")*
_atom_site.count("Cartn_y")*
_atom_site.count("Cartn_z")==0)
{
loop_ = false;
cerr<<"Warning! Missing one of the following _atom_site data items: group_PDB, label_atom_id, label_atom_id, auth_asym_id/label_asym_id, auth_seq_id/label_seq_id, Cartn_x, Cartn_y, Cartn_z"<<endl;
continue;
}
}
line_vec.clear();
split(line,line_vec);
if (line_vec[_atom_site["group_PDB"]]!="ATOM" && (het_opt==0 ||
line_vec[_atom_site["group_PDB"]]!="HETATM")) continue;
alt_id=".";
if (_atom_site.count("label_alt_id")) // in 39.4 % of entries
alt_id=line_vec[_atom_site["label_alt_id"]];
if (alt_id!="." && alt_id!="A") continue;
atom=line_vec[_atom_site["label_atom_id"]];
if (atom[0]=='"') atom=atom.substr(1);
if (atom.size() && atom[atom.size()-1]=='"')
atom=atom.substr(0,atom.size()-1);
if (atom.size()==0) continue;
if (atom.size()==1) atom=" "+atom+" ";
else if (atom.size()==2) atom=" "+atom+" "; // wrong for sidechain H
else if (atom.size()==3) atom=" "+atom;
else if (atom.size()>=5) continue;
AA=line_vec[_atom_site["label_comp_id"]]; // residue name
if (AA.size()==1) AA=" "+AA;
else if (AA.size()==2) AA=" " +AA;
else if (AA.size()>=4) continue;
if (atom_opt=="auto")
select_atom=(atom==" CA ");
else select_atom=(atom==atom_opt);
if (!select_atom) continue;
if (_atom_site.count("auth_asym_id"))
asym_id=line_vec[_atom_site["auth_asym_id"]];
else asym_id=line_vec[_atom_site["label_asym_id"]];
if (asym_id==".") asym_id=" ";
if (_atom_site.count("pdbx_PDB_model_num") &&
model_index!=line_vec[_atom_site["pdbx_PDB_model_num"]])
{
model_index=line_vec[_atom_site["pdbx_PDB_model_num"]];
if (PDB_lines.size() && ter_opt>=1) break;
if (PDB_lines.size()==0 || split_opt>=1)
{
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
prev_asym_id=asym_id;
if (split_opt==1 && ter_opt==0) chainID_list.push_back(
':'+model_index);
else if (split_opt==2 && ter_opt==0)
chainID_list.push_back(':'+model_index+':'+asym_id);
else if (split_opt==2 && ter_opt==1)
chainID_list.push_back(':'+asym_id);
}
}
if (prev_asym_id!=asym_id)
{
if (prev_asym_id!="" && ter_opt>=2) break;
if (split_opt>=2)
{
PDB_lines.push_back(tmp_str_vec);
mol_vec.push_back(0);
if (split_opt==1 && ter_opt==0) chainID_list.push_back(
':'+model_index);
else if (split_opt==2 && ter_opt==0)
chainID_list.push_back(':'+model_index+':'+asym_id);
else if (split_opt==2 && ter_opt==1)
chainID_list.push_back(':'+asym_id);
}
}
if (prev_asym_id!=asym_id) prev_asym_id=asym_id;
if (AA[0]==' ' && (AA[1]=='D'||AA[1]==' ')) mol_vec.back()++;
else mol_vec.back()--;
if (_atom_site.count("auth_seq_id"))
resi=line_vec[_atom_site["auth_seq_id"]];
else resi=line_vec[_atom_site["label_seq_id"]];
if (_atom_site.count("pdbx_PDB_ins_code") &&
line_vec[_atom_site["pdbx_PDB_ins_code"]]!="?")
resi+=line_vec[_atom_site["pdbx_PDB_ins_code"]][0];
else resi+=" ";
if (prev_resi==resi)
cerr<<"Warning! Duplicated residue "<<resi<<endl;
prev_resi=resi;
i++;
i8_stream<<"ATOM "
<<setw(5)<<i<<" "<<atom<<" "<<AA<<" "<<asym_id[0]
<<setw(5)<<resi.substr(0,5)<<" "
<<setw(8)<<line_vec[_atom_site["Cartn_x"]]
<<setw(8)<<line_vec[_atom_site["Cartn_y"]]
<<setw(8)<<line_vec[_atom_site["Cartn_z"]];
PDB_lines.back().push_back(i8_stream.str());
i8_stream.str(string());
}
_atom_site.clear();
line_vec.clear();
alt_id.clear();
asym_id.clear();
AA.clear();
}
fin.close();
line.clear();
if (!split_opt) chainID_list.push_back("");
return PDB_lines.size();
}
/* read fasta file from filename. sequence is stored into FASTA_lines
* while sequence name is stored into chainID_list.
* if ter_opt >=1, only read the first sequence.
* if ter_opt ==0, read all sequences.
* if split_opt >=1 and ter_opt ==0, each sequence is a separate entry.
* if split_opt ==0 and ter_opt ==0, all sequences are combined into one */
size_t get_FASTA_lines(const string filename,
vector<vector<string> >&FASTA_lines, vector<string> &chainID_list,
vector<int> &mol_vec, const int ter_opt=3, const int split_opt=0)
{
string line;
vector<string> tmp_str_vec;
int l;
ifstream fin;
fin.open(filename.c_str());
while (fin.good())
{
getline(fin, line);
if (line.size()==0 || line[0]=='#') continue;
if (line[0]=='>')
{
if (FASTA_lines.size())
{
if (ter_opt) break;
if (split_opt==0) continue;
}
FASTA_lines.push_back(tmp_str_vec);
FASTA_lines.back().push_back("");
mol_vec.push_back(0);
if (ter_opt==0 && split_opt)
{
line[0]=':';
chainID_list.push_back(line);
}
else chainID_list.push_back("");
}
else
{
FASTA_lines.back()[0]+=line;
for (l=0;l<line.size();l++) mol_vec.back()+=
('a'<=line[l] && line[l]<='z')-('A'<=line[l] && line[l]<='Z');
}
}
line.clear();
fin.close();
return FASTA_lines.size();
}
/* extract pairwise sequence alignment from residue index vectors,
* assuming that "sequence" contains two empty strings.
* return length of alignment, including gap. */
int extract_aln_from_resi(vector<string> &sequence, char *seqx, char *seqy,
const vector<string> resi_vec1, const vector<string> resi_vec2,
const int byresi_opt)
{
sequence.clear();
sequence.push_back("");
sequence.push_back("");
int i1=0; // positions in resi_vec1
int i2=0; // positions in resi_vec2
int xlen=resi_vec1.size();
int ylen=resi_vec2.size();
map<char,int> chainID_map1;
map<char,int> chainID_map2;
if (byresi_opt==3)
{
vector<char> chainID_vec;
char chainID;
int i;
for (i=0;i<xlen;i++)
{
chainID=resi_vec1[i][5];
if (!chainID_vec.size()|| chainID_vec.back()!=chainID)
{
chainID_vec.push_back(chainID);
chainID_map1[chainID]=chainID_vec.size();
}
}
chainID_vec.clear();
for (i=0;i<ylen;i++)
{
chainID=resi_vec2[i][5];
if (!chainID_vec.size()|| chainID_vec.back()!=chainID)
{
chainID_vec.push_back(chainID);
chainID_map2[chainID]=chainID_vec.size();
}
}
chainID_vec.clear();
}
while(i1<xlen && i2<ylen)
{
if ((byresi_opt<=2 && resi_vec1[i1]==resi_vec2[i2]) || (byresi_opt==3
&& resi_vec1[i1].substr(0,5)==resi_vec2[i2].substr(0,5)
&& chainID_map1[resi_vec1[i1][5]]==chainID_map2[resi_vec2[i2][5]]))
{
sequence[0]+=seqx[i1++];
sequence[1]+=seqy[i2++];
}
else if (atoi(resi_vec1[i1].substr(0,4).c_str())<=
atoi(resi_vec2[i2].substr(0,4).c_str()))
{
sequence[0]+=seqx[i1++];
sequence[1]+='-';
}
else
{
sequence[0]+='-';
sequence[1]+=seqy[i2++];
}
}
chainID_map1.clear();
chainID_map2.clear();
return sequence[0].size();
}
int read_PDB(const vector<string> &PDB_lines, double **a, char *seq,
vector<string> &resi_vec, const int byresi_opt)
{
int i;
for (i=0;i<PDB_lines.size();i++)
{
a[i][0] = atof(PDB_lines[i].substr(30, 8).c_str());
a[i][1] = atof(PDB_lines[i].substr(38, 8).c_str());
a[i][2] = atof(PDB_lines[i].substr(46, 8).c_str());
seq[i] = AAmap(PDB_lines[i].substr(17, 3));
if (byresi_opt>=2) resi_vec.push_back(PDB_lines[i].substr(22,5)+
PDB_lines[i][21]);
if (byresi_opt==1) resi_vec.push_back(PDB_lines[i].substr(22,5));
}
seq[i]='\0';
return i;
}
double dist(double x[3], double y[3])
{
double d1=x[0]-y[0];
double d2=x[1]-y[1];
double d3=x[2]-y[2];
return (d1*d1 + d2*d2 + d3*d3);
}
double dot(double *a, double *b)
{
return (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]);
}
void transform(double t[3], double u[3][3], double *x, double *x1)
{
x1[0]=t[0]+dot(&u[0][0], x);
x1[1]=t[1]+dot(&u[1][0], x);
x1[2]=t[2]+dot(&u[2][0], x);
}
void do_rotation(double **x, double **x1, int len, double t[3], double u[3][3])
{
for(int i=0; i<len; i++)
{
transform(t, u, &x[i][0], &x1[i][0]);
}
}
/* strip white space at the begining or end of string */
string Trim(const string &inputString)
{
string result = inputString;
int idxBegin = inputString.find_first_not_of(" \n\r\t");
int idxEnd = inputString.find_last_not_of(" \n\r\t");
if (idxBegin >= 0 && idxEnd >= 0)
result = inputString.substr(idxBegin, idxEnd + 1 - idxBegin);
return result;
}
/* read user specified pairwise alignment from 'fname_lign' to 'sequence'.
* This function should only be called by main function, as it will
* terminate a program if wrong alignment is given */
void read_user_alignment(vector<string>&sequence, const string &fname_lign,
const int i_opt)
{
if (fname_lign == "")
PrintErrorAndQuit("Please provide a file name for option -i!");
// open alignment file
int n_p = 0;// number of structures in alignment file
string line;
ifstream fileIn(fname_lign.c_str());
if (fileIn.is_open())
{
while (fileIn.good())
{
getline(fileIn, line);
if (line.compare(0, 1, ">") == 0)// Flag for a new structure
{
if (n_p >= 2) break;
sequence.push_back("");
n_p++;
}
else if (n_p > 0 && line!="") sequence.back()+=line;
}
fileIn.close();
}
else PrintErrorAndQuit("ERROR! Alignment file does not exist.");
if (n_p < 2)
PrintErrorAndQuit("ERROR: Fasta format is wrong, two proteins should be included.");
if (sequence[0].size() != sequence[1].size())
PrintErrorAndQuit("ERROR! FASTA file is wrong. The length in alignment should be equal for the two aligned proteins.");
if (i_opt==3)
{
int aligned_resNum=0;
for (int i=0;i<sequence[0].size();i++)
aligned_resNum+=(sequence[0][i]!='-' && sequence[1][i]!='-');
if (aligned_resNum<3)
PrintErrorAndQuit("ERROR! Superposition is undefined for <3 aligned residues.");
}
line.clear();
return;
}
/* read list of entries from 'name' to 'chain_list'.
* dir_opt is the folder name (prefix).
* suffix_opt is the file name extension (suffix_opt).
* This function should only be called by main function, as it will
* terminate a program if wrong alignment is given */
void file2chainlist(vector<string>&chain_list, const string &name,
const string &dir_opt, const string &suffix_opt)
{
ifstream fp(name.c_str());
if (! fp.is_open())
PrintErrorAndQuit(("Can not open file: "+name+'\n').c_str());
string line;
while (fp.good())
{
getline(fp, line);
if (! line.size()) continue;
chain_list.push_back(dir_opt+Trim(line)+suffix_opt);
}
fp.close();
line.clear();
}
/**************************************************************************
Implemetation of Kabsch algoritm for finding the best rotation matrix
---------------------------------------------------------------------------
x - x(i,m) are coordinates of atom m in set x (input)
y - y(i,m) are coordinates of atom m in set y (input)
n - n is number of atom pairs (input)
mode - 0:calculate rms only (input)
1:calculate u,t only (takes medium)
2:calculate rms,u,t (takes longer)
rms - sum of w*(ux+t-y)**2 over all atom pairs (output)
u - u(i,j) is rotation matrix for best superposition (output)
t - t(i) is translation vector for best superposition (output)
**************************************************************************/
bool Kabsch(double **x, double **y, int n, int mode, double *rms,
double t[3], double u[3][3])
{
int i, j, m, m1, l, k;
double e0, rms1, d, h, g;
double cth, sth, sqrth, p, det, sigma;
double xc[3], yc[3];
double a[3][3], b[3][3], r[3][3], e[3], rr[6], ss[6];
double sqrt3 = 1.73205080756888, tol = 0.01;
int ip[] = { 0, 1, 3, 1, 2, 4, 3, 4, 5 };
int ip2312[] = { 1, 2, 0, 1 };
int a_failed = 0, b_failed = 0;
double epsilon = 0.00000001;
//initializtation
*rms = 0;
rms1 = 0;
e0 = 0;
double c1[3], c2[3];
double s1[3], s2[3];