updated to jalview 2.1 and begun ArchiveClient/VamsasClient/VamsasStore updates.
[jalview.git] / src / jalview / analysis / AlignSeq.java
1 /*
2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 */
19 package jalview.analysis;
20
21 import jalview.datamodel.SequenceI;
22
23 import jalview.schemes.*;
24
25 import jalview.util.*;
26
27 import java.awt.*;
28
29 import java.util.*;
30
31
32 /**
33  *
34  *
35  * @author $author$
36  * @version $Revision$
37  */
38 public class AlignSeq
39 {
40     /** DOCUMENT ME!! */
41     public static java.util.Hashtable dnaHash = new java.util.Hashtable();
42
43     static
44     {
45         dnaHash.put("C", new Integer(0));
46         dnaHash.put("T", new Integer(1));
47         dnaHash.put("A", new Integer(2));
48         dnaHash.put("G", new Integer(3));
49         dnaHash.put("-", new Integer(4));
50     }
51
52     static String[] dna = { "C", "T", "A", "G", "-" };
53     static String[] pep =
54     {
55         "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F",
56         "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-"
57     };
58     int[][] score;
59     int[][] E;
60     int[][] F;
61     int[][] traceback;
62     int[] seq1;
63     int[] seq2;
64     SequenceI s1;
65     SequenceI s2;
66     public String s1str;
67     public String s2str;
68     int maxi;
69     int maxj;
70     int[] aseq1;
71     int[] aseq2;
72     public String astr1="";
73     public String astr2="";
74
75     /** DOCUMENT ME!! */
76     public int seq1start;
77
78     /** DOCUMENT ME!! */
79     public int seq1end;
80
81     /** DOCUMENT ME!! */
82     public int seq2start;
83
84     /** DOCUMENT ME!! */
85     public int seq2end;
86     int count;
87
88     /** DOCUMENT ME!! */
89     public int maxscore;
90     float pid;
91     int prev = 0;
92     int gapOpen = 120;
93     int gapExtend = 20;
94     int[][] lookup = ResidueProperties.getBLOSUM62();
95     String[] intToStr = pep;
96     int defInt = 23;
97     StringBuffer output = new StringBuffer();
98     String type;
99
100     /**
101      * Creates a new AlignSeq object.
102      *
103      * @param s1 DOCUMENT ME!
104      * @param s2 DOCUMENT ME!
105      * @param type DOCUMENT ME!
106      */
107     public AlignSeq(SequenceI s1, SequenceI s2, String type)
108     {
109         SeqInit(s1, s1.getSequence(), s2,  s2.getSequence(), type);
110     }
111
112     /**
113      * Creates a new AlignSeq object.
114      *
115      * @param s1 DOCUMENT ME!
116      * @param s2 DOCUMENT ME!
117      * @param type DOCUMENT ME!
118      */
119     public AlignSeq(SequenceI s1,
120                     String string1,
121                     SequenceI s2,
122                     String string2,
123                     String type)
124     {
125         SeqInit(s1, string1, s2,  string2,  type);
126     }
127
128     /**
129      * DOCUMENT ME!
130      *
131      * @return DOCUMENT ME!
132      */
133     public int getMaxScore()
134     {
135         return maxscore;
136     }
137
138     /**
139      * DOCUMENT ME!
140      *
141      * @return DOCUMENT ME!
142      */
143     public int getSeq2Start()
144     {
145         return seq2start;
146     }
147
148     /**
149      * DOCUMENT ME!
150      *
151      * @return DOCUMENT ME!
152      */
153     public int getSeq2End()
154     {
155         return seq2end;
156     }
157
158     /**
159      * DOCUMENT ME!
160      *
161      * @return DOCUMENT ME!
162      */
163     public int getSeq1Start()
164     {
165         return seq1start;
166     }
167
168     /**
169      * DOCUMENT ME!
170      *
171      * @return DOCUMENT ME!
172      */
173     public int getSeq1End()
174     {
175         return seq1end;
176     }
177
178     /**
179      * DOCUMENT ME!
180      *
181      * @return DOCUMENT ME!
182      */
183     public String getOutput()
184     {
185         return output.toString();
186     }
187
188     /**
189      * DOCUMENT ME!
190      *
191      * @return DOCUMENT ME!
192      */
193     public String getAStr1()
194     {
195         return astr1;
196     }
197
198     /**
199      * DOCUMENT ME!
200      *
201      * @return DOCUMENT ME!
202      */
203     public String getAStr2()
204     {
205         return astr2;
206     }
207
208     /**
209      * DOCUMENT ME!
210      *
211      * @return DOCUMENT ME!
212      */
213     public int[] getASeq1()
214     {
215         return aseq1;
216     }
217
218     /**
219      * DOCUMENT ME!
220      *
221      * @return DOCUMENT ME!
222      */
223     public int[] getASeq2()
224     {
225         return aseq2;
226     }
227
228     /**
229      * DOCUMENT ME!
230      *
231      * @return DOCUMENT ME!
232      */
233     public SequenceI getS1()
234     {
235         return s1;
236     }
237
238     /**
239      * DOCUMENT ME!
240      *
241      * @return DOCUMENT ME!
242      */
243     public SequenceI getS2()
244     {
245         return s2;
246     }
247
248     /**
249      * DOCUMENT ME!
250      *
251      * @param s1 DOCUMENT ME!
252      * @param s2 DOCUMENT ME!
253      * @param type DOCUMENT ME!
254      */
255     public void SeqInit(SequenceI s1,
256                         String string1,
257                         SequenceI s2,
258                         String string2,
259                         String type)
260     {
261
262         s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
263         s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
264
265         if(s1str.length()==0 || s2str.length()==0)
266         {
267           System.out.println("ALL GAPS: " +
268                              (s1str.length()==0?s1.getName():" ")
269                              +(s2str.length()==0?s2.getName():""));
270           return;
271         }
272
273         this.s1 = s1;
274         this.s2 = s2;
275
276         this.type = type;
277
278         if (type.equals("pep"))
279         {
280             lookup = ResidueProperties.getBLOSUM62();
281             intToStr = pep;
282             defInt = 23;
283         }
284         else if (type.equals("dna"))
285         {
286             lookup = ResidueProperties.getDNA();
287             intToStr = dna;
288             defInt = 4;
289         }
290         else
291         {
292             output.append("Wrong type = dna or pep only");
293             System.exit(0);
294         }
295
296         //System.out.println("lookuip " + rt.freeMemory() + " "+  rt.totalMemory());
297         seq1 = new int[s1str.length()];
298
299         //System.out.println("seq1 " + rt.freeMemory() +" "  + rt.totalMemory());
300         seq2 = new int[s2str.length()];
301
302         //System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
303         score = new int[s1str.length()][s2str.length()];
304
305         //System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
306         E = new int[s1str.length()][s2str.length()];
307
308         //System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
309         F = new int[s1str.length()][s2str.length()];
310         traceback = new int[s1str.length()][s2str.length()];
311
312         //System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
313         seq1 = stringToInt(s1str, type);
314
315         //System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
316         seq2 = stringToInt(s2str, type);
317
318         //System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
319         //   long tstart = System.currentTimeMillis();
320         //    calcScoreMatrix();
321         //long tend = System.currentTimeMillis();
322         //System.out.println("Time take to calculate score matrix = " + (tend-tstart) + " ms");
323         //   printScoreMatrix(score);
324         //System.out.println();
325         //printScoreMatrix(traceback);
326         //System.out.println();
327         //  printScoreMatrix(E);
328         //System.out.println();
329         ///printScoreMatrix(F);
330         //System.out.println();
331         // tstart = System.currentTimeMillis();
332         //traceAlignment();
333         //tend = System.currentTimeMillis();
334         //System.out.println("Time take to traceback alignment = " + (tend-tstart) + " ms");
335     }
336
337     /**
338      * DOCUMENT ME!
339      */
340     public void traceAlignment()
341     {
342         // Find the maximum score along the rhs or bottom row
343         int max = -9999;
344
345         for (int i = 0; i < seq1.length; i++)
346         {
347             if (score[i][seq2.length - 1] > max)
348             {
349                 max = score[i][seq2.length - 1];
350                 maxi = i;
351                 maxj = seq2.length - 1;
352             }
353         }
354
355         for (int j = 0; j < seq2.length; j++)
356         {
357             if (score[seq1.length - 1][j] > max)
358             {
359                 max = score[seq1.length - 1][j];
360                 maxi = seq1.length - 1;
361                 maxj = j;
362             }
363         }
364
365         //  System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
366         int i = maxi;
367         int j = maxj;
368         int trace;
369         maxscore = score[i][j] / 10;
370
371         seq1end = maxi + 1;
372         seq2end = maxj + 1;
373
374         aseq1 = new int[seq1.length + seq2.length];
375         aseq2 = new int[seq1.length + seq2.length];
376
377         count = (seq1.length + seq2.length) - 1;
378
379         while ((i > 0) && (j > 0))
380         {
381             if ((aseq1[count] != defInt) && (i >= 0))
382             {
383                 aseq1[count] = seq1[i];
384                 astr1 = intToStr[seq1[i]] + astr1;
385             }
386
387             if ((aseq2[count] != defInt) && (j > 0))
388             {
389                 aseq2[count] = seq2[j];
390                 astr2 = intToStr[seq2[j]] + astr2;
391             }
392
393             trace = findTrace(i, j);
394
395             if (trace == 0)
396             {
397                 i--;
398                 j--;
399             }
400             else if (trace == 1)
401             {
402                 j--;
403                 aseq1[count] = defInt;
404                 astr1 = "-" + astr1.substring(1);
405             }
406             else if (trace == -1)
407             {
408                 i--;
409                 aseq2[count] = defInt;
410                 astr2 = "-" + astr2.substring(1);
411             }
412
413             count--;
414         }
415
416         seq1start = i + 1;
417         seq2start = j + 1;
418
419         if (aseq1[count] != defInt)
420         {
421             aseq1[count] = seq1[i];
422             astr1 = intToStr[seq1[i]] + astr1;
423         }
424
425         if (aseq2[count] != defInt)
426         {
427             aseq2[count] = seq2[j];
428             astr2 = intToStr[seq2[j]] + astr2;
429         }
430     }
431
432     /**
433      * DOCUMENT ME!
434      */
435     public void printAlignment(java.io.PrintStream os)
436     {
437         // Find the biggest id length for formatting purposes
438         int maxid = s1.getName().length();
439
440         if (s2.getName().length() > maxid)
441         {
442             maxid = s2.getName().length();
443         }
444
445         int len = 72 - maxid - 1;
446         int nochunks = ((aseq1.length - count) / len) + 1;
447         pid = 0;
448
449         output.append("Score = " + score[maxi][maxj] + "\n");
450         output.append("Length of alignment = " + (aseq1.length - count) + "\n");
451         output.append("Sequence ");
452         output.append(new Format("%" + maxid + "s").form(s1.getName()));
453         output.append(" :  " + s1.getStart() + " - " + s1.getEnd() + " (Sequence length = " +
454             s1str.length() + ")\n");
455         output .append("Sequence ");
456         output.append(new Format("%" + maxid + "s").form(s2.getName()));
457         output.append(" :  " + s2.getStart() + " - " + s2.getEnd() + " (Sequence length = " +
458             s2str.length() + ")\n\n");
459
460         for (int j = 0; j < nochunks; j++)
461         {
462             // Print the first aligned sequence
463             output.append(new Format("%" + (maxid) + "s").form(s1.getName()) + " ");
464
465             for (int i = 0; i < len; i++)
466             {
467                 if ((count + i + (j * len)) < aseq1.length)
468                 {
469                     output.append(new Format("%s").form(intToStr[aseq1[count + i +
470                             (j * len)]]));
471                 }
472             }
473
474             output.append("\n");
475             output.append(new Format("%" + (maxid) + "s").form(" ") + " ");
476
477             // Print out the matching chars
478             for (int i = 0; i < len; i++)
479             {
480                 if ((count + i + (j * len)) < aseq1.length)
481                 {
482                     if (intToStr[aseq1[count + i + (j * len)]].equals(
483                                 intToStr[aseq2[count + i + (j * len)]]) &&
484                             !intToStr[aseq1[count + i + (j * len)]].equals("-"))
485                     {
486                         pid++;
487                         output.append("|");
488                     }
489                     else if (type.equals("pep"))
490                     {
491                         if (ResidueProperties.getPAM250(
492                                     intToStr[aseq1[count + i + (j * len)]],
493                                     intToStr[aseq2[count + i + (j * len)]]) > 0)
494                         {
495                             output.append(".");
496                         }
497                         else
498                         {
499                             output.append(" ");
500                         }
501                     }
502                     else
503                     {
504                         output.append(" ");
505                     }
506                 }
507             }
508
509             // Now print the second aligned sequence
510             output = output.append("\n");
511             output = output.append(new Format("%" + (maxid) + "s").form(s2.getName()) + " ");
512
513             for (int i = 0; i < len; i++)
514             {
515                 if ((count + i + (j * len)) < aseq1.length)
516                 {
517                     output .append(new Format("%s").form(intToStr[aseq2[count + i +
518                             (j * len)]]));
519                 }
520             }
521
522             output = output .append("\n\n");
523         }
524
525         pid = pid / (float) (aseq1.length - count) * 100;
526         output = output.append(new Format("Percentage ID = %2.2f\n\n").form(pid));
527
528         try{
529           os.print(output.toString());
530         }catch(Exception ex){}
531     }
532
533     /**
534      * DOCUMENT ME!
535      *
536      * @param mat DOCUMENT ME!
537      */
538     public void printScoreMatrix(int[][] mat)
539     {
540         int n = seq1.length;
541         int m = seq2.length;
542
543         for (int i = 0; i < n; i++)
544         {
545             // Print the top sequence
546             if (i == 0)
547             {
548                 Format.print(System.out, "%8s", s2str.substring(0, 1));
549
550                 for (int jj = 1; jj < m; jj++)
551                 {
552                     Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
553                 }
554
555                 System.out.println();
556             }
557
558             for (int j = 0; j < m; j++)
559             {
560                 if (j == 0)
561                 {
562                     Format.print(System.out, "%3s", s1str.substring(i, i + 1));
563                 }
564
565                 Format.print(System.out, "%3d ", mat[i][j] / 10);
566             }
567
568             System.out.println();
569         }
570     }
571
572     /**
573      * DOCUMENT ME!
574      *
575      * @param i DOCUMENT ME!
576      * @param j DOCUMENT ME!
577      *
578      * @return DOCUMENT ME!
579      */
580     public int findTrace(int i, int j)
581     {
582         int t = 0;
583         int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
584
585         if (F[i][j] > max)
586         {
587             max = F[i][j];
588             t = -1;
589         }
590         else if (F[i][j] == max)
591         {
592             if (prev == -1)
593             {
594                 max = F[i][j];
595                 t = -1;
596             }
597         }
598
599         if (E[i][j] >= max)
600         {
601             max = E[i][j];
602             t = 1;
603         }
604         else if (E[i][j] == max)
605         {
606             if (prev == 1)
607             {
608                 max = E[i][j];
609                 t = 1;
610             }
611         }
612
613         prev = t;
614
615         return t;
616     }
617
618     /**
619      * DOCUMENT ME!
620      */
621     public void calcScoreMatrix()
622     {
623         int n = seq1.length;
624         int m = seq2.length;
625
626         // top left hand element
627         score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
628         E[0][0] = -gapExtend;
629         F[0][0] = 0;
630
631         // Calculate the top row first
632         for (int j = 1; j < m; j++)
633         {
634             // What should these values be? 0 maybe
635             E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
636             F[0][j] = -gapExtend;
637
638             score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen,
639                     -gapExtend);
640
641             traceback[0][j] = 1;
642         }
643
644         // Now do the left hand column
645         for (int i = 1; i < n; i++)
646         {
647             E[i][0] = -gapOpen;
648             F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
649
650             score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
651             traceback[i][0] = -1;
652         }
653
654         // Now do all the other rows
655         for (int i = 1; i < n; i++)
656         {
657             for (int j = 1; j < m; j++)
658             {
659                 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] -
660                         gapExtend);
661                 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] -
662                         gapExtend);
663
664                 score[i][j] = max(score[i - 1][j - 1] +
665                         (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
666                 traceback[i][j] = findTrace(i, j);
667             }
668         }
669     }
670
671
672
673     /**
674      * DOCUMENT ME!
675      *
676      * @param gapChar DOCUMENT ME!
677      * @param seq DOCUMENT ME!
678      *
679      * @return DOCUMENT ME!
680      */
681     public static String extractGaps(String gapChar, String seq)
682     {
683         StringTokenizer str = new StringTokenizer(seq, gapChar);
684         StringBuffer newString = new StringBuffer();
685
686         while (str.hasMoreTokens())
687         {
688             newString.append( str.nextToken() );
689         }
690
691         return newString.toString();
692     }
693
694     /**
695      * DOCUMENT ME!
696      *
697      * @param i1 DOCUMENT ME!
698      * @param i2 DOCUMENT ME!
699      * @param i3 DOCUMENT ME!
700      *
701      * @return DOCUMENT ME!
702      */
703     public int max(int i1, int i2, int i3)
704     {
705         int max = i1;
706
707         if (i2 > i1)
708         {
709             max = i2;
710         }
711
712         if (i3 > max)
713         {
714             max = i3;
715         }
716
717         return max;
718     }
719
720     /**
721      * DOCUMENT ME!
722      *
723      * @param i1 DOCUMENT ME!
724      * @param i2 DOCUMENT ME!
725      *
726      * @return DOCUMENT ME!
727      */
728     public int max(int i1, int i2)
729     {
730         int max = i1;
731
732         if (i2 > i1)
733         {
734             max = i2;
735         }
736
737         return max;
738     }
739
740     /**
741      * DOCUMENT ME!
742      *
743      * @param s DOCUMENT ME!
744      * @param type DOCUMENT ME!
745      *
746      * @return DOCUMENT ME!
747      */
748     public int[] stringToInt(String s, String type)
749     {
750         int[] seq1 = new int[s.length()];
751
752         for (int i = 0; i < s.length(); i++)
753         {
754             String ss = s.substring(i, i + 1).toUpperCase();
755
756             try
757             {
758                 if (type.equals("pep"))
759                 {
760                     seq1[i] = ((Integer) ResidueProperties.aaHash.get(ss)).intValue();
761                 }
762                 else if (type.equals("dna"))
763                 {
764                     seq1[i] = ((Integer) dnaHash.get(ss)).intValue();
765                 }
766
767                 if (seq1[i] > 23)
768                 {
769                     seq1[i] = 23;
770                 }
771             }
772             catch (Exception e)
773             {
774                 if (type.equals("dna"))
775                 {
776                     seq1[i] = 4;
777                 }
778                 else
779                 {
780                     seq1[i] = 23;
781                 }
782             }
783         }
784
785         return seq1;
786     }
787
788     /**
789      * DOCUMENT ME!
790      *
791      * @param g DOCUMENT ME!
792      * @param mat DOCUMENT ME!
793      * @param n DOCUMENT ME!
794      * @param m DOCUMENT ME!
795      * @param psize DOCUMENT ME!
796      */
797     public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
798         int psize)
799     {
800         int max = -1000;
801         int min = 1000;
802
803         for (int i = 0; i < n; i++)
804         {
805             for (int j = 0; j < m; j++)
806             {
807                 if (mat[i][j] >= max)
808                 {
809                     max = mat[i][j];
810                 }
811
812                 if (mat[i][j] <= min)
813                 {
814                     min = mat[i][j];
815                 }
816             }
817         }
818
819         System.out.println(max + " " + min);
820
821         for (int i = 0; i < n; i++)
822         {
823             for (int j = 0; j < m; j++)
824             {
825                 int x = psize * i;
826                 int y = psize * j;
827
828                 //      System.out.println(mat[i][j]);
829                 float score = (float) (mat[i][j] - min) / (float) (max - min);
830                 g.setColor(new Color(score, 0, 0));
831                 g.fillRect(x, y, psize, psize);
832
833                 //      System.out.println(x + " " + y + " " + score);
834             }
835         }
836     }
837 }