JAL-1517 source formatting
[jalview.git] / src / jalview / analysis / AlignSeq.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.analysis;
22
23 import java.util.*;
24
25 import java.awt.*;
26
27 import jalview.datamodel.*;
28 import jalview.schemes.*;
29 import jalview.util.*;
30
31 /**
32  * 
33  * 
34  * @author $author$
35  * @version $Revision$
36  */
37 public class AlignSeq
38 {
39   public static final String PEP = "pep";
40
41   public static final String DNA = "dna";
42
43   static String[] dna =
44   { "A", "C", "G", "T", "-" };
45
46   // "C", "T", "A", "G", "-"};
47   static String[] pep =
48   { "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F",
49       "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" };
50
51   int[][] score;
52
53   int[][] E;
54
55   int[][] F;
56
57   int[][] traceback;
58
59   int[] seq1;
60
61   int[] seq2;
62
63   SequenceI s1;
64
65   SequenceI s2;
66
67   public String s1str;
68
69   public String s2str;
70
71   int maxi;
72
73   int maxj;
74
75   int[] aseq1;
76
77   int[] aseq2;
78
79   public String astr1 = "";
80
81   public String astr2 = "";
82
83   /** DOCUMENT ME!! */
84   public int seq1start;
85
86   /** DOCUMENT ME!! */
87   public int seq1end;
88
89   /** DOCUMENT ME!! */
90   public int seq2start;
91
92   /** DOCUMENT ME!! */
93   public int seq2end;
94
95   int count;
96
97   /** DOCUMENT ME!! */
98   public int maxscore;
99
100   float pid;
101
102   int prev = 0;
103
104   int gapOpen = 120;
105
106   int gapExtend = 20;
107
108   int[][] lookup = ResidueProperties.getBLOSUM62();
109
110   String[] intToStr = pep;
111
112   int defInt = 23;
113
114   StringBuffer output = new StringBuffer();
115
116   String type;
117
118   private int[] charToInt;
119
120   /**
121    * Creates a new AlignSeq object.
122    * 
123    * @param s1
124    *          DOCUMENT ME!
125    * @param s2
126    *          DOCUMENT ME!
127    * @param type
128    *          DOCUMENT ME!
129    */
130   public AlignSeq(SequenceI s1, SequenceI s2, String type)
131   {
132     SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
133             type);
134   }
135
136   /**
137    * Creates a new AlignSeq object.
138    * 
139    * @param s1
140    *          DOCUMENT ME!
141    * @param s2
142    *          DOCUMENT ME!
143    * @param type
144    *          DOCUMENT ME!
145    */
146   public AlignSeq(SequenceI s1, String string1, SequenceI s2,
147           String string2, String type)
148   {
149     SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
150   }
151
152   /**
153    * DOCUMENT ME!
154    * 
155    * @return DOCUMENT ME!
156    */
157   public int getMaxScore()
158   {
159     return maxscore;
160   }
161
162   /**
163    * DOCUMENT ME!
164    * 
165    * @return DOCUMENT ME!
166    */
167   public int getSeq2Start()
168   {
169     return seq2start;
170   }
171
172   /**
173    * DOCUMENT ME!
174    * 
175    * @return DOCUMENT ME!
176    */
177   public int getSeq2End()
178   {
179     return seq2end;
180   }
181
182   /**
183    * DOCUMENT ME!
184    * 
185    * @return DOCUMENT ME!
186    */
187   public int getSeq1Start()
188   {
189     return seq1start;
190   }
191
192   /**
193    * DOCUMENT ME!
194    * 
195    * @return DOCUMENT ME!
196    */
197   public int getSeq1End()
198   {
199     return seq1end;
200   }
201
202   /**
203    * DOCUMENT ME!
204    * 
205    * @return DOCUMENT ME!
206    */
207   public String getOutput()
208   {
209     return output.toString();
210   }
211
212   /**
213    * DOCUMENT ME!
214    * 
215    * @return DOCUMENT ME!
216    */
217   public String getAStr1()
218   {
219     return astr1;
220   }
221
222   /**
223    * DOCUMENT ME!
224    * 
225    * @return DOCUMENT ME!
226    */
227   public String getAStr2()
228   {
229     return astr2;
230   }
231
232   /**
233    * DOCUMENT ME!
234    * 
235    * @return DOCUMENT ME!
236    */
237   public int[] getASeq1()
238   {
239     return aseq1;
240   }
241
242   /**
243    * DOCUMENT ME!
244    * 
245    * @return DOCUMENT ME!
246    */
247   public int[] getASeq2()
248   {
249     return aseq2;
250   }
251
252   /**
253    * DOCUMENT ME!
254    * 
255    * @return DOCUMENT ME!
256    */
257   public SequenceI getS1()
258   {
259     return s1;
260   }
261
262   /**
263    * DOCUMENT ME!
264    * 
265    * @return DOCUMENT ME!
266    */
267   public SequenceI getS2()
268   {
269     return s2;
270   }
271
272   /**
273    * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
274    * 
275    * @param s1
276    *          - sequence 1
277    * @param string1
278    *          - string to use for s1
279    * @param s2
280    *          - sequence 2
281    * @param string2
282    *          - string to use for s2
283    * @param type
284    *          DNA or PEPTIDE
285    */
286   public void SeqInit(SequenceI s1, String string1, SequenceI s2,
287           String string2, String type)
288   {
289     this.s1 = s1;
290     this.s2 = s2;
291     setDefaultParams(type);
292     SeqInit(string1, string2);
293   }
294
295   /**
296    * Construct score matrix for sequences with custom substitution matrix
297    * 
298    * @param s1
299    *          - sequence 1
300    * @param string1
301    *          - string to use for s1
302    * @param s2
303    *          - sequence 2
304    * @param string2
305    *          - string to use for s2
306    * @param scoreMatrix
307    *          - substitution matrix to use for alignment
308    */
309   public void SeqInit(SequenceI s1, String string1, SequenceI s2,
310           String string2, ScoreMatrix scoreMatrix)
311   {
312     this.s1 = s1;
313     this.s2 = s2;
314     setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
315     lookup = scoreMatrix.getMatrix();
316   }
317
318   /**
319    * construct score matrix for string1 and string2 (after removing any existing
320    * gaps
321    * 
322    * @param string1
323    * @param string2
324    */
325   private void SeqInit(String string1, String string2)
326   {
327     s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
328     s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
329
330     if (s1str.length() == 0 || s2str.length() == 0)
331     {
332       output.append("ALL GAPS: "
333               + (s1str.length() == 0 ? s1.getName() : " ")
334               + (s2str.length() == 0 ? s2.getName() : ""));
335       return;
336     }
337
338     // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
339     seq1 = new int[s1str.length()];
340
341     // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
342     seq2 = new int[s2str.length()];
343
344     // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
345     score = new int[s1str.length()][s2str.length()];
346
347     // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
348     E = new int[s1str.length()][s2str.length()];
349
350     // System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
351     F = new int[s1str.length()][s2str.length()];
352     traceback = new int[s1str.length()][s2str.length()];
353
354     // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
355     seq1 = stringToInt(s1str, type);
356
357     // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
358     seq2 = stringToInt(s2str, type);
359
360     // System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
361     // long tstart = System.currentTimeMillis();
362     // calcScoreMatrix();
363     // long tend = System.currentTimeMillis();
364     // System.out.println("Time take to calculate score matrix = " +
365     // (tend-tstart) + " ms");
366     // printScoreMatrix(score);
367     // System.out.println();
368     // printScoreMatrix(traceback);
369     // System.out.println();
370     // printScoreMatrix(E);
371     // System.out.println();
372     // /printScoreMatrix(F);
373     // System.out.println();
374     // tstart = System.currentTimeMillis();
375     // traceAlignment();
376     // tend = System.currentTimeMillis();
377     // System.out.println("Time take to traceback alignment = " + (tend-tstart)
378     // + " ms");
379   }
380
381   private void setDefaultParams(String type)
382   {
383     setType(type);
384
385     if (type.equals(AlignSeq.PEP))
386     {
387       lookup = ResidueProperties.getDefaultPeptideMatrix();
388     }
389     else if (type.equals(AlignSeq.DNA))
390     {
391       lookup = ResidueProperties.getDefaultDnaMatrix();
392     }
393   }
394
395   private void setType(String type2)
396   {
397     this.type = type2;
398     if (type.equals(AlignSeq.PEP))
399     {
400       intToStr = pep;
401       charToInt = ResidueProperties.aaIndex;
402       defInt = ResidueProperties.maxProteinIndex;
403     }
404     else if (type.equals(AlignSeq.DNA))
405     {
406       intToStr = dna;
407       charToInt = ResidueProperties.nucleotideIndex;
408       defInt = ResidueProperties.maxNucleotideIndex;
409     }
410     else
411     {
412       output.append("Wrong type = dna or pep only");
413       throw new Error("Unknown Type " + type2
414               + " - dna or pep are the only allowed values.");
415     }
416   }
417
418   /**
419    * DOCUMENT ME!
420    */
421   public void traceAlignment()
422   {
423     // Find the maximum score along the rhs or bottom row
424     int max = -9999;
425
426     for (int i = 0; i < seq1.length; i++)
427     {
428       if (score[i][seq2.length - 1] > max)
429       {
430         max = score[i][seq2.length - 1];
431         maxi = i;
432         maxj = seq2.length - 1;
433       }
434     }
435
436     for (int j = 0; j < seq2.length; j++)
437     {
438       if (score[seq1.length - 1][j] > max)
439       {
440         max = score[seq1.length - 1][j];
441         maxi = seq1.length - 1;
442         maxj = j;
443       }
444     }
445
446     // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
447     int i = maxi;
448     int j = maxj;
449     int trace;
450     maxscore = score[i][j] / 10;
451
452     seq1end = maxi + 1;
453     seq2end = maxj + 1;
454
455     aseq1 = new int[seq1.length + seq2.length];
456     aseq2 = new int[seq1.length + seq2.length];
457
458     count = (seq1.length + seq2.length) - 1;
459
460     while ((i > 0) && (j > 0))
461     {
462       if ((aseq1[count] != defInt) && (i >= 0))
463       {
464         aseq1[count] = seq1[i];
465         astr1 = s1str.charAt(i) + astr1;
466       }
467
468       if ((aseq2[count] != defInt) && (j > 0))
469       {
470         aseq2[count] = seq2[j];
471         astr2 = s2str.charAt(j) + astr2;
472       }
473
474       trace = findTrace(i, j);
475
476       if (trace == 0)
477       {
478         i--;
479         j--;
480       }
481       else if (trace == 1)
482       {
483         j--;
484         aseq1[count] = defInt;
485         astr1 = "-" + astr1.substring(1);
486       }
487       else if (trace == -1)
488       {
489         i--;
490         aseq2[count] = defInt;
491         astr2 = "-" + astr2.substring(1);
492       }
493
494       count--;
495     }
496
497     seq1start = i + 1;
498     seq2start = j + 1;
499
500     if (aseq1[count] != defInt)
501     {
502       aseq1[count] = seq1[i];
503       astr1 = s1str.charAt(i) + astr1;
504     }
505
506     if (aseq2[count] != defInt)
507     {
508       aseq2[count] = seq2[j];
509       astr2 = s2str.charAt(j) + astr2;
510     }
511   }
512
513   /**
514    * DOCUMENT ME!
515    */
516   public void printAlignment(java.io.PrintStream os)
517   {
518     // TODO: Use original sequence characters rather than re-translated
519     // characters in output
520     // Find the biggest id length for formatting purposes
521     String s1id = s1.getName(), s2id = s2.getName();
522     int maxid = s1.getName().length();
523     if (s2.getName().length() > maxid)
524     {
525       maxid = s2.getName().length();
526     }
527     if (maxid > 30)
528     {
529       maxid = 30;
530       // JAL-527 - truncate the sequence ids
531       if (s1.getName().length() > maxid)
532       {
533         s1id = s1.getName().substring(0, 30);
534       }
535       if (s2.getName().length() > maxid)
536       {
537         s2id = s2.getName().substring(0, 30);
538       }
539     }
540     int len = 72 - maxid - 1;
541     int nochunks = ((aseq1.length - count) / len) + 1;
542     pid = 0;
543
544     output.append("Score = " + score[maxi][maxj] + "\n");
545     output.append("Length of alignment = " + (aseq1.length - count) + "\n");
546     output.append("Sequence ");
547     output.append(new Format("%" + maxid + "s").form(s1.getName()));
548     output.append(" :  " + s1.getStart() + " - " + s1.getEnd()
549             + " (Sequence length = " + s1str.length() + ")\n");
550     output.append("Sequence ");
551     output.append(new Format("%" + maxid + "s").form(s2.getName()));
552     output.append(" :  " + s2.getStart() + " - " + s2.getEnd()
553             + " (Sequence length = " + s2str.length() + ")\n\n");
554
555     for (int j = 0; j < nochunks; j++)
556     {
557       // Print the first aligned sequence
558       output.append(new Format("%" + (maxid) + "s").form(s1id) + " ");
559
560       for (int i = 0; i < len; i++)
561       {
562         if ((i + (j * len)) < astr1.length())
563         {
564           output.append(astr1.charAt(i + (j * len)));
565         }
566       }
567
568       output.append("\n");
569       output.append(new Format("%" + (maxid) + "s").form(" ") + " ");
570
571       // Print out the matching chars
572       for (int i = 0; i < len; i++)
573       {
574         if ((i + (j * len)) < astr1.length())
575         {
576           if (astr1.charAt(i + (j * len)) == astr2.charAt(i + (j * len))
577                   && !jalview.util.Comparison.isGap(astr1.charAt(i
578                           + (j * len))))
579           {
580             pid++;
581             output.append("|");
582           }
583           else if (type.equals("pep"))
584           {
585             if (ResidueProperties.getPAM250(astr1.charAt(i + (j * len)),
586                     astr2.charAt(i + (j * len))) > 0)
587             {
588               output.append(".");
589             }
590             else
591             {
592               output.append(" ");
593             }
594           }
595           else
596           {
597             output.append(" ");
598           }
599         }
600       }
601
602       // Now print the second aligned sequence
603       output = output.append("\n");
604       output = output.append(new Format("%" + (maxid) + "s").form(s2id)
605               + " ");
606
607       for (int i = 0; i < len; i++)
608       {
609         if ((i + (j * len)) < astr2.length())
610         {
611           output.append(astr2.charAt(i + (j * len)));
612         }
613       }
614
615       output = output.append("\n\n");
616     }
617
618     pid = pid / (float) (aseq1.length - count) * 100;
619     output = output.append(new Format("Percentage ID = %2.2f\n\n")
620             .form(pid));
621
622     try
623     {
624       os.print(output.toString());
625     } catch (Exception ex)
626     {
627     }
628   }
629
630   /**
631    * DOCUMENT ME!
632    * 
633    * @param mat
634    *          DOCUMENT ME!
635    */
636   public void printScoreMatrix(int[][] mat)
637   {
638     int n = seq1.length;
639     int m = seq2.length;
640
641     for (int i = 0; i < n; i++)
642     {
643       // Print the top sequence
644       if (i == 0)
645       {
646         Format.print(System.out, "%8s", s2str.substring(0, 1));
647
648         for (int jj = 1; jj < m; jj++)
649         {
650           Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
651         }
652
653         System.out.println();
654       }
655
656       for (int j = 0; j < m; j++)
657       {
658         if (j == 0)
659         {
660           Format.print(System.out, "%3s", s1str.substring(i, i + 1));
661         }
662
663         Format.print(System.out, "%3d ", mat[i][j] / 10);
664       }
665
666       System.out.println();
667     }
668   }
669
670   /**
671    * DOCUMENT ME!
672    * 
673    * @param i
674    *          DOCUMENT ME!
675    * @param j
676    *          DOCUMENT ME!
677    * 
678    * @return DOCUMENT ME!
679    */
680   public int findTrace(int i, int j)
681   {
682     int t = 0;
683     int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
684
685     if (F[i][j] > max)
686     {
687       max = F[i][j];
688       t = -1;
689     }
690     else if (F[i][j] == max)
691     {
692       if (prev == -1)
693       {
694         max = F[i][j];
695         t = -1;
696       }
697     }
698
699     if (E[i][j] >= max)
700     {
701       max = E[i][j];
702       t = 1;
703     }
704     else if (E[i][j] == max)
705     {
706       if (prev == 1)
707       {
708         max = E[i][j];
709         t = 1;
710       }
711     }
712
713     prev = t;
714
715     return t;
716   }
717
718   /**
719    * DOCUMENT ME!
720    */
721   public void calcScoreMatrix()
722   {
723     int n = seq1.length;
724     int m = seq2.length;
725
726     // top left hand element
727     score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
728     E[0][0] = -gapExtend;
729     F[0][0] = 0;
730
731     // Calculate the top row first
732     for (int j = 1; j < m; j++)
733     {
734       // What should these values be? 0 maybe
735       E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
736       F[0][j] = -gapExtend;
737
738       score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
739
740       traceback[0][j] = 1;
741     }
742
743     // Now do the left hand column
744     for (int i = 1; i < n; i++)
745     {
746       E[i][0] = -gapOpen;
747       F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
748
749       score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
750       traceback[i][0] = -1;
751     }
752
753     // Now do all the other rows
754     for (int i = 1; i < n; i++)
755     {
756       for (int j = 1; j < m; j++)
757       {
758         E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
759         F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
760
761         score[i][j] = max(score[i - 1][j - 1]
762                 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
763         traceback[i][j] = findTrace(i, j);
764       }
765     }
766   }
767
768   /**
769    * DOCUMENT ME!
770    * 
771    * @param gapChar
772    *          DOCUMENT ME!
773    * @param seq
774    *          DOCUMENT ME!
775    * 
776    * @return DOCUMENT ME!
777    */
778   public static String extractGaps(String gapChar, String seq)
779   {
780     StringTokenizer str = new StringTokenizer(seq, gapChar);
781     StringBuffer newString = new StringBuffer();
782
783     while (str.hasMoreTokens())
784     {
785       newString.append(str.nextToken());
786     }
787
788     return newString.toString();
789   }
790
791   /**
792    * DOCUMENT ME!
793    * 
794    * @param i1
795    *          DOCUMENT ME!
796    * @param i2
797    *          DOCUMENT ME!
798    * @param i3
799    *          DOCUMENT ME!
800    * 
801    * @return DOCUMENT ME!
802    */
803   public int max(int i1, int i2, int i3)
804   {
805     int max = i1;
806
807     if (i2 > i1)
808     {
809       max = i2;
810     }
811
812     if (i3 > max)
813     {
814       max = i3;
815     }
816
817     return max;
818   }
819
820   /**
821    * DOCUMENT ME!
822    * 
823    * @param i1
824    *          DOCUMENT ME!
825    * @param i2
826    *          DOCUMENT ME!
827    * 
828    * @return DOCUMENT ME!
829    */
830   public int max(int i1, int i2)
831   {
832     int max = i1;
833
834     if (i2 > i1)
835     {
836       max = i2;
837     }
838
839     return max;
840   }
841
842   /**
843    * DOCUMENT ME!
844    * 
845    * @param s
846    *          DOCUMENT ME!
847    * @param type
848    *          DOCUMENT ME!
849    * 
850    * @return DOCUMENT ME!
851    */
852   public int[] stringToInt(String s, String type)
853   {
854     int[] seq1 = new int[s.length()];
855
856     for (int i = 0; i < s.length(); i++)
857     {
858       // String ss = s.substring(i, i + 1).toUpperCase();
859       char c = s.charAt(i);
860       if ('a' <= c && c <= 'z')
861       {
862         // TO UPPERCASE !!!
863         c -= ('a' - 'A');
864       }
865
866       try
867       {
868         seq1[i] = charToInt[c]; // set accordingly from setType
869         if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
870                                              // peptides, or 4 for NA.
871         {
872           seq1[i] = defInt;
873         }
874
875       } catch (Exception e)
876       {
877         seq1[i] = defInt;
878       }
879     }
880
881     return seq1;
882   }
883
884   /**
885    * DOCUMENT ME!
886    * 
887    * @param g
888    *          DOCUMENT ME!
889    * @param mat
890    *          DOCUMENT ME!
891    * @param n
892    *          DOCUMENT ME!
893    * @param m
894    *          DOCUMENT ME!
895    * @param psize
896    *          DOCUMENT ME!
897    */
898   public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
899           int psize)
900   {
901     int max = -1000;
902     int min = 1000;
903
904     for (int i = 0; i < n; i++)
905     {
906       for (int j = 0; j < m; j++)
907       {
908         if (mat[i][j] >= max)
909         {
910           max = mat[i][j];
911         }
912
913         if (mat[i][j] <= min)
914         {
915           min = mat[i][j];
916         }
917       }
918     }
919
920     System.out.println(max + " " + min);
921
922     for (int i = 0; i < n; i++)
923     {
924       for (int j = 0; j < m; j++)
925       {
926         int x = psize * i;
927         int y = psize * j;
928
929         // System.out.println(mat[i][j]);
930         float score = (float) (mat[i][j] - min) / (float) (max - min);
931         g.setColor(new Color(score, 0, 0));
932         g.fillRect(x, y, psize, psize);
933
934         // System.out.println(x + " " + y + " " + score);
935       }
936     }
937   }
938
939   /**
940    * Compute a globally optimal needleman and wunsch alignment between two
941    * sequences
942    * 
943    * @param s1
944    * @param s2
945    * @param type
946    *          AlignSeq.DNA or AlignSeq.PEP
947    */
948   public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
949           String type)
950   {
951     AlignSeq as = new AlignSeq(s1, s2, type);
952
953     as.calcScoreMatrix();
954     as.traceAlignment();
955     return as;
956   }
957
958   /**
959    * 
960    * @return mapping from positions in S1 to corresponding positions in S2
961    */
962   public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
963   {
964     ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
965     int pdbpos = s2.getStart() + getSeq2Start() - 2;
966     int alignpos = s1.getStart() + getSeq1Start() - 2;
967     int lp2 = pdbpos - 3, lp1 = alignpos - 3;
968     boolean lastmatch = false;
969     // and now trace the alignment onto the atom set.
970     for (int i = 0; i < astr1.length(); i++)
971     {
972       char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
973       if (c1 != '-')
974       {
975         alignpos++;
976       }
977
978       if (c2 != '-')
979       {
980         pdbpos++;
981       }
982
983       if (allowmismatch || c1 == c2)
984       {
985         lastmatch = true;
986         // extend mapping interval.
987         if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
988         {
989           as1.add(Integer.valueOf(alignpos));
990           as2.add(Integer.valueOf(pdbpos));
991         }
992         lp1 = alignpos;
993         lp2 = pdbpos;
994       }
995       else
996       {
997         lastmatch = false;
998       }
999     }
1000     // construct range pairs
1001     int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1002             .size() + (lastmatch ? 1 : 0)];
1003     int i = 0;
1004     for (Integer ip : as1)
1005     {
1006       mapseq1[i++] = ip;
1007     }
1008     ;
1009     i = 0;
1010     for (Integer ip : as2)
1011     {
1012       mapseq2[i++] = ip;
1013     }
1014     ;
1015     if (lastmatch)
1016     {
1017       mapseq1[mapseq1.length - 1] = alignpos;
1018       mapseq2[mapseq2.length - 1] = pdbpos;
1019     }
1020     MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1021
1022     jalview.datamodel.Mapping mapping = new Mapping(map);
1023     mapping.setTo(s2);
1024     return mapping;
1025   }
1026
1027   /**
1028    * compute the PID vector used by the redundancy filter.
1029    * 
1030    * @param originalSequences
1031    *          - sequences in alignment that are to filtered
1032    * @param omitHidden
1033    *          - null or strings to be analysed (typically, visible portion of
1034    *          each sequence in alignment)
1035    * @param start
1036    *          - first column in window for calculation
1037    * @param end
1038    *          - last column in window for calculation
1039    * @param ungapped
1040    *          - if true then use ungapped sequence to compute PID
1041    * @return vector containing maximum PID for i-th sequence and any sequences
1042    *         longer than that seuqence
1043    */
1044   public static float[] computeRedundancyMatrix(
1045           SequenceI[] originalSequences, String[] omitHidden, int start,
1046           int end, boolean ungapped)
1047   {
1048     int height = originalSequences.length;
1049     float[] redundancy = new float[height];
1050     int[] lngth = new int[height];
1051     for (int i = 0; i < height; i++)
1052     {
1053       redundancy[i] = 0f;
1054       lngth[i] = -1;
1055     }
1056
1057     // long start = System.currentTimeMillis();
1058
1059     float pid;
1060     String seqi, seqj;
1061     for (int i = 0; i < height; i++)
1062     {
1063
1064       for (int j = 0; j < i; j++)
1065       {
1066         if (i == j)
1067         {
1068           continue;
1069         }
1070
1071         if (omitHidden == null)
1072         {
1073           seqi = originalSequences[i].getSequenceAsString(start, end);
1074           seqj = originalSequences[j].getSequenceAsString(start, end);
1075         }
1076         else
1077         {
1078           seqi = omitHidden[i];
1079           seqj = omitHidden[j];
1080         }
1081         if (lngth[i] == -1)
1082         {
1083           String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1084           lngth[i] = ug.length();
1085           if (ungapped)
1086           {
1087             seqi = ug;
1088           }
1089         }
1090         if (lngth[j] == -1)
1091         {
1092           String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1093           lngth[j] = ug.length();
1094           if (ungapped)
1095           {
1096             seqj = ug;
1097           }
1098         }
1099         pid = Comparison.PID(seqi, seqj);
1100
1101         // use real sequence length rather than string length
1102         if (lngth[j] < lngth[i])
1103         {
1104           redundancy[j] = Math.max(pid, redundancy[j]);
1105         }
1106         else
1107         {
1108           redundancy[i] = Math.max(pid, redundancy[i]);
1109         }
1110
1111       }
1112     }
1113     return redundancy;
1114   }
1115 }