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