2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.analysis;
26 import jalview.datamodel.*;
27 import jalview.schemes.*;
28 import jalview.util.*;
38 public static final String PEP = "pep";
40 public static final String DNA = "dna";
43 { "A", "C", "G", "T", "-" };
45 // "C", "T", "A", "G", "-"};
47 { "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F",
48 "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" };
78 public String astr1 = "";
80 public String astr2 = "";
107 int[][] lookup = ResidueProperties.getBLOSUM62();
109 String[] intToStr = pep;
113 StringBuffer output = new StringBuffer();
117 private int[] charToInt;
120 * Creates a new AlignSeq object.
129 public AlignSeq(SequenceI s1, SequenceI s2, String type)
131 SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
136 * Creates a new AlignSeq object.
145 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
146 String string2, String type)
148 SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
154 * @return DOCUMENT ME!
156 public int getMaxScore()
164 * @return DOCUMENT ME!
166 public int getSeq2Start()
174 * @return DOCUMENT ME!
176 public int getSeq2End()
184 * @return DOCUMENT ME!
186 public int getSeq1Start()
194 * @return DOCUMENT ME!
196 public int getSeq1End()
204 * @return DOCUMENT ME!
206 public String getOutput()
208 return output.toString();
214 * @return DOCUMENT ME!
216 public String getAStr1()
224 * @return DOCUMENT ME!
226 public String getAStr2()
234 * @return DOCUMENT ME!
236 public int[] getASeq1()
244 * @return DOCUMENT ME!
246 public int[] getASeq2()
254 * @return DOCUMENT ME!
256 public SequenceI getS1()
264 * @return DOCUMENT ME!
266 public SequenceI getS2()
272 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
273 * @param s1 - sequence 1
274 * @param string1 - string to use for s1
275 * @param s2 - sequence 2
276 * @param string2 - string to use for s2
280 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
281 String string2, String type)
285 setDefaultParams(type);
286 SeqInit(string1, string2);
290 * Construct score matrix for sequences with custom substitution matrix
291 * @param s1 - sequence 1
292 * @param string1 - string to use for s1
293 * @param s2 - sequence 2
294 * @param string2 - string to use for s2
295 * @param scoreMatrix - substitution matrix to use for alignment
297 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
298 String string2, ScoreMatrix scoreMatrix)
302 setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
303 lookup = scoreMatrix.getMatrix();
307 * construct score matrix for string1 and string2 (after removing any existing
313 private void SeqInit(String string1, String string2)
315 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
316 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
318 if (s1str.length() == 0 || s2str.length() == 0)
320 output.append("ALL GAPS: "
321 + (s1str.length() == 0 ? s1.getName() : " ")
322 + (s2str.length() == 0 ? s2.getName() : ""));
326 // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
327 seq1 = new int[s1str.length()];
329 // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
330 seq2 = new int[s2str.length()];
332 // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
333 score = new int[s1str.length()][s2str.length()];
335 // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
336 E = new int[s1str.length()][s2str.length()];
338 // System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
339 F = new int[s1str.length()][s2str.length()];
340 traceback = new int[s1str.length()][s2str.length()];
342 // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
343 seq1 = stringToInt(s1str, type);
345 // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
346 seq2 = stringToInt(s2str, type);
348 // System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
349 // long tstart = System.currentTimeMillis();
350 // calcScoreMatrix();
351 // long tend = System.currentTimeMillis();
352 // System.out.println("Time take to calculate score matrix = " +
353 // (tend-tstart) + " ms");
354 // printScoreMatrix(score);
355 // System.out.println();
356 // printScoreMatrix(traceback);
357 // System.out.println();
358 // printScoreMatrix(E);
359 // System.out.println();
360 // /printScoreMatrix(F);
361 // System.out.println();
362 // tstart = System.currentTimeMillis();
364 // tend = System.currentTimeMillis();
365 // System.out.println("Time take to traceback alignment = " + (tend-tstart)
369 private void setDefaultParams(String type)
373 if (type.equals(AlignSeq.PEP))
375 lookup = ResidueProperties.getDefaultPeptideMatrix();
377 else if (type.equals(AlignSeq.DNA))
379 lookup = ResidueProperties.getDefaultDnaMatrix();
383 private void setType(String type2)
386 if (type.equals(AlignSeq.PEP))
389 charToInt = ResidueProperties.aaIndex;
390 defInt = ResidueProperties.maxProteinIndex;
392 else if (type.equals(AlignSeq.DNA))
395 charToInt = ResidueProperties.nucleotideIndex;
396 defInt = ResidueProperties.maxNucleotideIndex;
400 output.append("Wrong type = dna or pep only");
401 throw new Error("Unknown Type " + type2
402 + " - dna or pep are the only allowed values.");
409 public void traceAlignment()
411 // Find the maximum score along the rhs or bottom row
414 for (int i = 0; i < seq1.length; i++)
416 if (score[i][seq2.length - 1] > max)
418 max = score[i][seq2.length - 1];
420 maxj = seq2.length - 1;
424 for (int j = 0; j < seq2.length; j++)
426 if (score[seq1.length - 1][j] > max)
428 max = score[seq1.length - 1][j];
429 maxi = seq1.length - 1;
434 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
438 maxscore = score[i][j] / 10;
443 aseq1 = new int[seq1.length + seq2.length];
444 aseq2 = new int[seq1.length + seq2.length];
446 count = (seq1.length + seq2.length) - 1;
448 while ((i > 0) && (j > 0))
450 if ((aseq1[count] != defInt) && (i >= 0))
452 aseq1[count] = seq1[i];
453 astr1 = s1str.charAt(i) + astr1;
456 if ((aseq2[count] != defInt) && (j > 0))
458 aseq2[count] = seq2[j];
459 astr2 = s2str.charAt(j) + astr2;
462 trace = findTrace(i, j);
472 aseq1[count] = defInt;
473 astr1 = "-" + astr1.substring(1);
475 else if (trace == -1)
478 aseq2[count] = defInt;
479 astr2 = "-" + astr2.substring(1);
488 if (aseq1[count] != defInt)
490 aseq1[count] = seq1[i];
491 astr1 = s1str.charAt(i) + astr1;
494 if (aseq2[count] != defInt)
496 aseq2[count] = seq2[j];
497 astr2 = s2str.charAt(j) + astr2;
504 public void printAlignment(java.io.PrintStream os)
506 // TODO: Use original sequence characters rather than re-translated
507 // characters in output
508 // Find the biggest id length for formatting purposes
509 String s1id = s1.getName(), s2id = s2.getName();
510 int maxid = s1.getName().length();
511 if (s2.getName().length() > maxid)
513 maxid = s2.getName().length();
518 // JAL-527 - truncate the sequence ids
519 if (s1.getName().length() > maxid)
521 s1id = s1.getName().substring(0, 30);
523 if (s2.getName().length() > maxid)
525 s2id = s2.getName().substring(0, 30);
528 int len = 72 - maxid - 1;
529 int nochunks = ((aseq1.length - count) / len) + 1;
532 output.append("Score = " + score[maxi][maxj] + "\n");
533 output.append("Length of alignment = " + (aseq1.length - count) + "\n");
534 output.append("Sequence ");
535 output.append(new Format("%" + maxid + "s").form(s1.getName()));
536 output.append(" : " + s1.getStart() + " - " + s1.getEnd()
537 + " (Sequence length = " + s1str.length() + ")\n");
538 output.append("Sequence ");
539 output.append(new Format("%" + maxid + "s").form(s2.getName()));
540 output.append(" : " + s2.getStart() + " - " + s2.getEnd()
541 + " (Sequence length = " + s2str.length() + ")\n\n");
543 for (int j = 0; j < nochunks; j++)
545 // Print the first aligned sequence
546 output.append(new Format("%" + (maxid) + "s").form(s1id) + " ");
548 for (int i = 0; i < len; i++)
550 if ((i + (j * len)) < astr1.length())
552 output.append(astr1.charAt(i + (j * len)));
557 output.append(new Format("%" + (maxid) + "s").form(" ") + " ");
559 // Print out the matching chars
560 for (int i = 0; i < len; i++)
562 if ((i + (j * len)) < astr1.length())
564 if (astr1.charAt(i + (j * len)) == astr2.charAt(i + (j * len))
565 && !jalview.util.Comparison.isGap(astr1.charAt(i
571 else if (type.equals("pep"))
573 if (ResidueProperties.getPAM250(astr1.charAt(i + (j * len)),
574 astr2.charAt(i + (j * len))) > 0)
590 // Now print the second aligned sequence
591 output = output.append("\n");
592 output = output.append(new Format("%" + (maxid) + "s").form(s2id)
595 for (int i = 0; i < len; i++)
597 if ((i + (j * len)) < astr2.length())
599 output.append(astr2.charAt(i + (j * len)));
603 output = output.append("\n\n");
606 pid = pid / (float) (aseq1.length - count) * 100;
607 output = output.append(new Format("Percentage ID = %2.2f\n\n")
612 os.print(output.toString());
613 } catch (Exception ex)
624 public void printScoreMatrix(int[][] mat)
629 for (int i = 0; i < n; i++)
631 // Print the top sequence
634 Format.print(System.out, "%8s", s2str.substring(0, 1));
636 for (int jj = 1; jj < m; jj++)
638 Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
641 System.out.println();
644 for (int j = 0; j < m; j++)
648 Format.print(System.out, "%3s", s1str.substring(i, i + 1));
651 Format.print(System.out, "%3d ", mat[i][j] / 10);
654 System.out.println();
666 * @return DOCUMENT ME!
668 public int findTrace(int i, int j)
671 int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
678 else if (F[i][j] == max)
692 else if (E[i][j] == max)
709 public void calcScoreMatrix()
714 // top left hand element
715 score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
716 E[0][0] = -gapExtend;
719 // Calculate the top row first
720 for (int j = 1; j < m; j++)
722 // What should these values be? 0 maybe
723 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
724 F[0][j] = -gapExtend;
726 score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
731 // Now do the left hand column
732 for (int i = 1; i < n; i++)
735 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
737 score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
738 traceback[i][0] = -1;
741 // Now do all the other rows
742 for (int i = 1; i < n; i++)
744 for (int j = 1; j < m; j++)
746 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
747 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
749 score[i][j] = max(score[i - 1][j - 1]
750 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
751 traceback[i][j] = findTrace(i, j);
764 * @return DOCUMENT ME!
766 public static String extractGaps(String gapChar, String seq)
768 StringTokenizer str = new StringTokenizer(seq, gapChar);
769 StringBuffer newString = new StringBuffer();
771 while (str.hasMoreTokens())
773 newString.append(str.nextToken());
776 return newString.toString();
789 * @return DOCUMENT ME!
791 public int max(int i1, int i2, int i3)
816 * @return DOCUMENT ME!
818 public int max(int i1, int i2)
838 * @return DOCUMENT ME!
840 public int[] stringToInt(String s, String type)
842 int[] seq1 = new int[s.length()];
844 for (int i = 0; i < s.length(); i++)
846 // String ss = s.substring(i, i + 1).toUpperCase();
847 char c = s.charAt(i);
848 if ('a' <= c && c <= 'z')
856 seq1[i] = charToInt[c]; // set accordingly from setType
857 if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
858 // peptides, or 4 for NA.
863 } catch (Exception e)
886 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
892 for (int i = 0; i < n; i++)
894 for (int j = 0; j < m; j++)
896 if (mat[i][j] >= max)
901 if (mat[i][j] <= min)
908 System.out.println(max + " " + min);
910 for (int i = 0; i < n; i++)
912 for (int j = 0; j < m; j++)
917 // System.out.println(mat[i][j]);
918 float score = (float) (mat[i][j] - min) / (float) (max - min);
919 g.setColor(new Color(score, 0, 0));
920 g.fillRect(x, y, psize, psize);
922 // System.out.println(x + " " + y + " " + score);
928 * Compute a globally optimal needleman and wunsch alignment between two
934 * AlignSeq.DNA or AlignSeq.PEP
936 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
939 AlignSeq as = new AlignSeq(s1, s2, type);
941 as.calcScoreMatrix();
948 * @return mapping from positions in S1 to corresponding positions in S2
950 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
952 ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
953 int pdbpos = s2.getStart() + getSeq2Start() - 2;
954 int alignpos = s1.getStart() + getSeq1Start() - 2;
955 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
956 boolean lastmatch = false;
957 // and now trace the alignment onto the atom set.
958 for (int i = 0; i < astr1.length(); i++)
960 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
971 if (allowmismatch || c1 == c2)
974 // extend mapping interval.
975 if (lp1 + 1 != alignpos || lp2+1 !=pdbpos)
977 as1.add(Integer.valueOf(alignpos));
978 as2.add(Integer.valueOf(pdbpos));
988 // construct range pairs
989 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
990 .size() + (lastmatch ? 1 : 0)];
992 for (Integer ip : as1)
998 for (Integer ip : as2)
1005 mapseq1[mapseq1.length - 1] = alignpos;
1006 mapseq2[mapseq2.length - 1] = pdbpos;
1008 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1010 jalview.datamodel.Mapping mapping = new Mapping(map);
1016 * compute the PID vector used by the redundancy filter.
1018 * @param originalSequences
1019 * - sequences in alignment that are to filtered
1021 * - null or strings to be analysed (typically, visible portion of
1022 * each sequence in alignment)
1024 * - first column in window for calculation
1026 * - last column in window for calculation
1028 * - if true then use ungapped sequence to compute PID
1029 * @return vector containing maximum PID for i-th sequence and any sequences
1030 * longer than that seuqence
1032 public static float[] computeRedundancyMatrix(
1033 SequenceI[] originalSequences, String[] omitHidden, int start,
1034 int end, boolean ungapped)
1036 int height = originalSequences.length;
1037 float[] redundancy = new float[height];
1038 int[] lngth = new int[height];
1039 for (int i = 0; i < height; i++)
1045 // long start = System.currentTimeMillis();
1049 for (int i = 0; i < height; i++)
1052 for (int j = 0; j < i; j++)
1059 if (omitHidden == null)
1061 seqi = originalSequences[i].getSequenceAsString(start, end);
1062 seqj = originalSequences[j].getSequenceAsString(start, end);
1066 seqi = omitHidden[i];
1067 seqj = omitHidden[j];
1071 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1072 lngth[i] = ug.length();
1080 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1081 lngth[j] = ug.length();
1087 pid = Comparison.PID(seqi, seqj);
1089 // use real sequence length rather than string length
1090 if (lngth[j] < lngth[i])
1092 redundancy[j] = Math.max(pid, redundancy[j]);
1096 redundancy[i] = Math.max(pid, redundancy[i]);