JAL-674 refactor method to match and transfer annotation between aligned
[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(MessageManager.formatMessage("error.unknown_type_dna_or_pep", new String[]{type2}));
414     }
415   }
416
417   /**
418    * DOCUMENT ME!
419    */
420   public void traceAlignment()
421   {
422     // Find the maximum score along the rhs or bottom row
423     int max = -9999;
424
425     for (int i = 0; i < seq1.length; i++)
426     {
427       if (score[i][seq2.length - 1] > max)
428       {
429         max = score[i][seq2.length - 1];
430         maxi = i;
431         maxj = seq2.length - 1;
432       }
433     }
434
435     for (int j = 0; j < seq2.length; j++)
436     {
437       if (score[seq1.length - 1][j] > max)
438       {
439         max = score[seq1.length - 1][j];
440         maxi = seq1.length - 1;
441         maxj = j;
442       }
443     }
444
445     // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
446     int i = maxi;
447     int j = maxj;
448     int trace;
449     maxscore = score[i][j] / 10;
450
451     seq1end = maxi + 1;
452     seq2end = maxj + 1;
453
454     aseq1 = new int[seq1.length + seq2.length];
455     aseq2 = new int[seq1.length + seq2.length];
456
457     count = (seq1.length + seq2.length) - 1;
458
459     while ((i > 0) && (j > 0))
460     {
461       if ((aseq1[count] != defInt) && (i >= 0))
462       {
463         aseq1[count] = seq1[i];
464         astr1 = s1str.charAt(i) + astr1;
465       }
466
467       if ((aseq2[count] != defInt) && (j > 0))
468       {
469         aseq2[count] = seq2[j];
470         astr2 = s2str.charAt(j) + astr2;
471       }
472
473       trace = findTrace(i, j);
474
475       if (trace == 0)
476       {
477         i--;
478         j--;
479       }
480       else if (trace == 1)
481       {
482         j--;
483         aseq1[count] = defInt;
484         astr1 = "-" + astr1.substring(1);
485       }
486       else if (trace == -1)
487       {
488         i--;
489         aseq2[count] = defInt;
490         astr2 = "-" + astr2.substring(1);
491       }
492
493       count--;
494     }
495
496     seq1start = i + 1;
497     seq2start = j + 1;
498
499     if (aseq1[count] != defInt)
500     {
501       aseq1[count] = seq1[i];
502       astr1 = s1str.charAt(i) + astr1;
503     }
504
505     if (aseq2[count] != defInt)
506     {
507       aseq2[count] = seq2[j];
508       astr2 = s2str.charAt(j) + astr2;
509     }
510   }
511
512   /**
513    * DOCUMENT ME!
514    */
515   public void printAlignment(java.io.PrintStream os)
516   {
517     // TODO: Use original sequence characters rather than re-translated
518     // characters in output
519     // Find the biggest id length for formatting purposes
520     String s1id = s1.getName(), s2id = s2.getName();
521     int maxid = s1.getName().length();
522     if (s2.getName().length() > maxid)
523     {
524       maxid = s2.getName().length();
525     }
526     if (maxid > 30)
527     {
528       maxid = 30;
529       // JAL-527 - truncate the sequence ids
530       if (s1.getName().length() > maxid)
531       {
532         s1id = s1.getName().substring(0, 30);
533       }
534       if (s2.getName().length() > maxid)
535       {
536         s2id = s2.getName().substring(0, 30);
537       }
538     }
539     int len = 72 - maxid - 1;
540     int nochunks = ((aseq1.length - count) / len) + 1;
541     pid = 0;
542
543     output.append("Score = " + score[maxi][maxj] + "\n");
544     output.append("Length of alignment = " + (aseq1.length - count) + "\n");
545     output.append("Sequence ");
546     output.append(new Format("%" + maxid + "s").form(s1.getName()));
547     output.append(" :  " + s1.getStart() + " - " + s1.getEnd()
548             + " (Sequence length = " + s1str.length() + ")\n");
549     output.append("Sequence ");
550     output.append(new Format("%" + maxid + "s").form(s2.getName()));
551     output.append(" :  " + s2.getStart() + " - " + s2.getEnd()
552             + " (Sequence length = " + s2str.length() + ")\n\n");
553
554     for (int j = 0; j < nochunks; j++)
555     {
556       // Print the first aligned sequence
557       output.append(new Format("%" + (maxid) + "s").form(s1id) + " ");
558
559       for (int i = 0; i < len; i++)
560       {
561         if ((i + (j * len)) < astr1.length())
562         {
563           output.append(astr1.charAt(i + (j * len)));
564         }
565       }
566
567       output.append("\n");
568       output.append(new Format("%" + (maxid) + "s").form(" ") + " ");
569
570       // Print out the matching chars
571       for (int i = 0; i < len; i++)
572       {
573         if ((i + (j * len)) < astr1.length())
574         {
575           if (astr1.charAt(i + (j * len)) == astr2.charAt(i + (j * len))
576                   && !jalview.util.Comparison.isGap(astr1.charAt(i
577                           + (j * len))))
578           {
579             pid++;
580             output.append("|");
581           }
582           else if (type.equals("pep"))
583           {
584             if (ResidueProperties.getPAM250(astr1.charAt(i + (j * len)),
585                     astr2.charAt(i + (j * len))) > 0)
586             {
587               output.append(".");
588             }
589             else
590             {
591               output.append(" ");
592             }
593           }
594           else
595           {
596             output.append(" ");
597           }
598         }
599       }
600
601       // Now print the second aligned sequence
602       output = output.append("\n");
603       output = output.append(new Format("%" + (maxid) + "s").form(s2id)
604               + " ");
605
606       for (int i = 0; i < len; i++)
607       {
608         if ((i + (j * len)) < astr2.length())
609         {
610           output.append(astr2.charAt(i + (j * len)));
611         }
612       }
613
614       output = output.append("\n\n");
615     }
616
617     pid = pid / (float) (aseq1.length - count) * 100;
618     output = output.append(new Format("Percentage ID = %2.2f\n\n")
619             .form(pid));
620
621     try
622     {
623       os.print(output.toString());
624     } catch (Exception ex)
625     {
626     }
627   }
628
629   /**
630    * DOCUMENT ME!
631    * 
632    * @param mat
633    *          DOCUMENT ME!
634    */
635   public void printScoreMatrix(int[][] mat)
636   {
637     int n = seq1.length;
638     int m = seq2.length;
639
640     for (int i = 0; i < n; i++)
641     {
642       // Print the top sequence
643       if (i == 0)
644       {
645         Format.print(System.out, "%8s", s2str.substring(0, 1));
646
647         for (int jj = 1; jj < m; jj++)
648         {
649           Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
650         }
651
652         System.out.println();
653       }
654
655       for (int j = 0; j < m; j++)
656       {
657         if (j == 0)
658         {
659           Format.print(System.out, "%3s", s1str.substring(i, i + 1));
660         }
661
662         Format.print(System.out, "%3d ", mat[i][j] / 10);
663       }
664
665       System.out.println();
666     }
667   }
668
669   /**
670    * DOCUMENT ME!
671    * 
672    * @param i
673    *          DOCUMENT ME!
674    * @param j
675    *          DOCUMENT ME!
676    * 
677    * @return DOCUMENT ME!
678    */
679   public int findTrace(int i, int j)
680   {
681     int t = 0;
682     int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
683
684     if (F[i][j] > max)
685     {
686       max = F[i][j];
687       t = -1;
688     }
689     else if (F[i][j] == max)
690     {
691       if (prev == -1)
692       {
693         max = F[i][j];
694         t = -1;
695       }
696     }
697
698     if (E[i][j] >= max)
699     {
700       max = E[i][j];
701       t = 1;
702     }
703     else if (E[i][j] == max)
704     {
705       if (prev == 1)
706       {
707         max = E[i][j];
708         t = 1;
709       }
710     }
711
712     prev = t;
713
714     return t;
715   }
716
717   /**
718    * DOCUMENT ME!
719    */
720   public void calcScoreMatrix()
721   {
722     int n = seq1.length;
723     int m = seq2.length;
724
725     // top left hand element
726     score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
727     E[0][0] = -gapExtend;
728     F[0][0] = 0;
729
730     // Calculate the top row first
731     for (int j = 1; j < m; j++)
732     {
733       // What should these values be? 0 maybe
734       E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
735       F[0][j] = -gapExtend;
736
737       score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
738
739       traceback[0][j] = 1;
740     }
741
742     // Now do the left hand column
743     for (int i = 1; i < n; i++)
744     {
745       E[i][0] = -gapOpen;
746       F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
747
748       score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
749       traceback[i][0] = -1;
750     }
751
752     // Now do all the other rows
753     for (int i = 1; i < n; i++)
754     {
755       for (int j = 1; j < m; j++)
756       {
757         E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
758         F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
759
760         score[i][j] = max(score[i - 1][j - 1]
761                 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
762         traceback[i][j] = findTrace(i, j);
763       }
764     }
765   }
766
767   /**
768    * DOCUMENT ME!
769    * 
770    * @param gapChar
771    *          DOCUMENT ME!
772    * @param seq
773    *          DOCUMENT ME!
774    * 
775    * @return DOCUMENT ME!
776    */
777   public static String extractGaps(String gapChar, String seq)
778   {
779     StringTokenizer str = new StringTokenizer(seq, gapChar);
780     StringBuffer newString = new StringBuffer();
781
782     while (str.hasMoreTokens())
783     {
784       newString.append(str.nextToken());
785     }
786
787     return newString.toString();
788   }
789
790   /**
791    * DOCUMENT ME!
792    * 
793    * @param i1
794    *          DOCUMENT ME!
795    * @param i2
796    *          DOCUMENT ME!
797    * @param i3
798    *          DOCUMENT ME!
799    * 
800    * @return DOCUMENT ME!
801    */
802   public int max(int i1, int i2, int i3)
803   {
804     int max = i1;
805
806     if (i2 > i1)
807     {
808       max = i2;
809     }
810
811     if (i3 > max)
812     {
813       max = i3;
814     }
815
816     return max;
817   }
818
819   /**
820    * DOCUMENT ME!
821    * 
822    * @param i1
823    *          DOCUMENT ME!
824    * @param i2
825    *          DOCUMENT ME!
826    * 
827    * @return DOCUMENT ME!
828    */
829   public int max(int i1, int i2)
830   {
831     int max = i1;
832
833     if (i2 > i1)
834     {
835       max = i2;
836     }
837
838     return max;
839   }
840
841   /**
842    * DOCUMENT ME!
843    * 
844    * @param s
845    *          DOCUMENT ME!
846    * @param type
847    *          DOCUMENT ME!
848    * 
849    * @return DOCUMENT ME!
850    */
851   public int[] stringToInt(String s, String type)
852   {
853     int[] seq1 = new int[s.length()];
854
855     for (int i = 0; i < s.length(); i++)
856     {
857       // String ss = s.substring(i, i + 1).toUpperCase();
858       char c = s.charAt(i);
859       if ('a' <= c && c <= 'z')
860       {
861         // TO UPPERCASE !!!
862         c -= ('a' - 'A');
863       }
864
865       try
866       {
867         seq1[i] = charToInt[c]; // set accordingly from setType
868         if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
869                                              // peptides, or 4 for NA.
870         {
871           seq1[i] = defInt;
872         }
873
874       } catch (Exception e)
875       {
876         seq1[i] = defInt;
877       }
878     }
879
880     return seq1;
881   }
882
883   /**
884    * DOCUMENT ME!
885    * 
886    * @param g
887    *          DOCUMENT ME!
888    * @param mat
889    *          DOCUMENT ME!
890    * @param n
891    *          DOCUMENT ME!
892    * @param m
893    *          DOCUMENT ME!
894    * @param psize
895    *          DOCUMENT ME!
896    */
897   public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
898           int psize)
899   {
900     int max = -1000;
901     int min = 1000;
902
903     for (int i = 0; i < n; i++)
904     {
905       for (int j = 0; j < m; j++)
906       {
907         if (mat[i][j] >= max)
908         {
909           max = mat[i][j];
910         }
911
912         if (mat[i][j] <= min)
913         {
914           min = mat[i][j];
915         }
916       }
917     }
918
919     System.out.println(max + " " + min);
920
921     for (int i = 0; i < n; i++)
922     {
923       for (int j = 0; j < m; j++)
924       {
925         int x = psize * i;
926         int y = psize * j;
927
928         // System.out.println(mat[i][j]);
929         float score = (float) (mat[i][j] - min) / (float) (max - min);
930         g.setColor(new Color(score, 0, 0));
931         g.fillRect(x, y, psize, psize);
932
933         // System.out.println(x + " " + y + " " + score);
934       }
935     }
936   }
937
938   /**
939    * Compute a globally optimal needleman and wunsch alignment between two
940    * sequences
941    * 
942    * @param s1
943    * @param s2
944    * @param type
945    *          AlignSeq.DNA or AlignSeq.PEP
946    */
947   public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
948           String type)
949   {
950     AlignSeq as = new AlignSeq(s1, s2, type);
951
952     as.calcScoreMatrix();
953     as.traceAlignment();
954     return as;
955   }
956
957   /**
958    * 
959    * @return mapping from positions in S1 to corresponding positions in S2
960    */
961   public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
962   {
963     ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
964     int pdbpos = s2.getStart() + getSeq2Start() - 2;
965     int alignpos = s1.getStart() + getSeq1Start() - 2;
966     int lp2 = pdbpos - 3, lp1 = alignpos - 3;
967     boolean lastmatch = false;
968     // and now trace the alignment onto the atom set.
969     for (int i = 0; i < astr1.length(); i++)
970     {
971       char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
972       if (c1 != '-')
973       {
974         alignpos++;
975       }
976
977       if (c2 != '-')
978       {
979         pdbpos++;
980       }
981
982       if (allowmismatch || c1 == c2)
983       {
984         lastmatch = true;
985         // extend mapping interval.
986         if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
987         {
988           as1.add(Integer.valueOf(alignpos));
989           as2.add(Integer.valueOf(pdbpos));
990         }
991         lp1 = alignpos;
992         lp2 = pdbpos;
993       }
994       else
995       {
996         lastmatch = false;
997       }
998     }
999     // construct range pairs
1000     int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1001             .size() + (lastmatch ? 1 : 0)];
1002     int i = 0;
1003     for (Integer ip : as1)
1004     {
1005       mapseq1[i++] = ip;
1006     }
1007     ;
1008     i = 0;
1009     for (Integer ip : as2)
1010     {
1011       mapseq2[i++] = ip;
1012     }
1013     ;
1014     if (lastmatch)
1015     {
1016       mapseq1[mapseq1.length - 1] = alignpos;
1017       mapseq2[mapseq2.length - 1] = pdbpos;
1018     }
1019     MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1020
1021     jalview.datamodel.Mapping mapping = new Mapping(map);
1022     mapping.setTo(s2);
1023     return mapping;
1024   }
1025
1026   /**
1027    * matches ochains against al and populates seqs with the best match between
1028    * each ochain and the set in al
1029    * 
1030    * @param ochains
1031    * @param al
1032    * @param dnaOrProtein
1033    * @param removeOldAnnots when true, old annotation is cleared before new annotation transferred
1034    */
1035   public static void replaceMatchingSeqsWith(List<SequenceI> seqs, List<AlignmentAnnotation> annotations, List<SequenceI> ochains,
1036           AlignmentI al, String dnaOrProtein, boolean removeOldAnnots)
1037   {
1038     if (al != null && al.getHeight() > 0)
1039     {
1040       ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1041       ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1042   
1043       for (SequenceI sq : ochains)
1044       {
1045         SequenceI bestm = null;
1046         AlignSeq bestaseq = null;
1047         int bestscore = 0;
1048         for (SequenceI msq : al.getSequences())
1049         {
1050           AlignSeq aseq = doGlobalNWAlignment(msq, sq,
1051                   dnaOrProtein);
1052           if (bestm == null || aseq.getMaxScore() > bestscore)
1053           {
1054             bestscore = aseq.getMaxScore();
1055             bestaseq = aseq;
1056             bestm = msq;
1057           }
1058         }
1059         System.out.println("Best Score for " + (matches.size() + 1) + " :"
1060                 + bestscore);
1061         matches.add(bestm);
1062         aligns.add(bestaseq);
1063         al.deleteSequence(bestm);
1064       }
1065       for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1066       {
1067         SequenceI sq, sp = seqs.get(p);
1068         int q;
1069         if ((q = ochains.indexOf(sp)) > -1)
1070         {
1071           seqs.set(p, sq = matches.get(q));
1072           sq.setName(sp.getName());
1073           sq.setDescription(sp.getDescription());
1074           Mapping sp2sq;
1075           sq.transferAnnotation(sp, sp2sq = aligns.get(q).getMappingFromS1(false));
1076           int inspos = -1;
1077           for (int ap = 0; ap < annotations.size();)
1078           {
1079             if (annotations.get(ap).sequenceRef == sp)
1080             {
1081               if (inspos == -1)
1082               {
1083                 inspos = ap;
1084               }
1085               if (removeOldAnnots) {
1086                 annotations.remove(ap);
1087               } else {
1088                 AlignmentAnnotation alan = annotations.get(ap);
1089                 alan.liftOver(sq, sp2sq);
1090                 alan.setSequenceRef(sq);
1091               }
1092             }
1093             else
1094             {
1095               ap++;
1096             }
1097           }
1098           if (sq.getAnnotation() != null)
1099           {
1100             annotations.addAll(inspos, Arrays.asList(sq.getAnnotation()));
1101           }
1102         }
1103       }
1104     }
1105   }
1106
1107   /**
1108    * compute the PID vector used by the redundancy filter.
1109    * 
1110    * @param originalSequences
1111    *          - sequences in alignment that are to filtered
1112    * @param omitHidden
1113    *          - null or strings to be analysed (typically, visible portion of
1114    *          each sequence in alignment)
1115    * @param start
1116    *          - first column in window for calculation
1117    * @param end
1118    *          - last column in window for calculation
1119    * @param ungapped
1120    *          - if true then use ungapped sequence to compute PID
1121    * @return vector containing maximum PID for i-th sequence and any sequences
1122    *         longer than that seuqence
1123    */
1124   public static float[] computeRedundancyMatrix(
1125           SequenceI[] originalSequences, String[] omitHidden, int start,
1126           int end, boolean ungapped)
1127   {
1128     int height = originalSequences.length;
1129     float[] redundancy = new float[height];
1130     int[] lngth = new int[height];
1131     for (int i = 0; i < height; i++)
1132     {
1133       redundancy[i] = 0f;
1134       lngth[i] = -1;
1135     }
1136
1137     // long start = System.currentTimeMillis();
1138
1139     float pid;
1140     String seqi, seqj;
1141     for (int i = 0; i < height; i++)
1142     {
1143
1144       for (int j = 0; j < i; j++)
1145       {
1146         if (i == j)
1147         {
1148           continue;
1149         }
1150
1151         if (omitHidden == null)
1152         {
1153           seqi = originalSequences[i].getSequenceAsString(start, end);
1154           seqj = originalSequences[j].getSequenceAsString(start, end);
1155         }
1156         else
1157         {
1158           seqi = omitHidden[i];
1159           seqj = omitHidden[j];
1160         }
1161         if (lngth[i] == -1)
1162         {
1163           String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1164           lngth[i] = ug.length();
1165           if (ungapped)
1166           {
1167             seqi = ug;
1168           }
1169         }
1170         if (lngth[j] == -1)
1171         {
1172           String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1173           lngth[j] = ug.length();
1174           if (ungapped)
1175           {
1176             seqj = ug;
1177           }
1178         }
1179         pid = Comparison.PID(seqi, seqj);
1180
1181         // use real sequence length rather than string length
1182         if (lngth[j] < lngth[i])
1183         {
1184           redundancy[j] = Math.max(pid, redundancy[j]);
1185         }
1186         else
1187         {
1188           redundancy[i] = Math.max(pid, redundancy[i]);
1189         }
1190
1191       }
1192     }
1193     return redundancy;
1194   }
1195 }