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