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;
27 import jalview.datamodel.*;
28 import jalview.schemes.*;
29 import jalview.util.*;
39 public static final String PEP = "pep";
41 public static final String DNA = "dna";
44 { "A", "C", "G", "T", "-" };
46 // "C", "T", "A", "G", "-"};
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", "-" };
79 public String astr1 = "";
81 public String astr2 = "";
108 int[][] lookup = ResidueProperties.getBLOSUM62();
110 String[] intToStr = pep;
114 StringBuffer output = new StringBuffer();
118 private int[] charToInt;
121 * Creates a new AlignSeq object.
130 public AlignSeq(SequenceI s1, SequenceI s2, String type)
132 SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
137 * Creates a new AlignSeq object.
146 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
147 String string2, String type)
149 SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
155 * @return DOCUMENT ME!
157 public int getMaxScore()
165 * @return DOCUMENT ME!
167 public int getSeq2Start()
175 * @return DOCUMENT ME!
177 public int getSeq2End()
185 * @return DOCUMENT ME!
187 public int getSeq1Start()
195 * @return DOCUMENT ME!
197 public int getSeq1End()
205 * @return DOCUMENT ME!
207 public String getOutput()
209 return output.toString();
215 * @return DOCUMENT ME!
217 public String getAStr1()
225 * @return DOCUMENT ME!
227 public String getAStr2()
235 * @return DOCUMENT ME!
237 public int[] getASeq1()
245 * @return DOCUMENT ME!
247 public int[] getASeq2()
255 * @return DOCUMENT ME!
257 public SequenceI getS1()
265 * @return DOCUMENT ME!
267 public SequenceI getS2()
273 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
278 * - string to use for s1
282 * - string to use for s2
286 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
287 String string2, String type)
291 setDefaultParams(type);
292 SeqInit(string1, string2);
296 * Construct score matrix for sequences with custom substitution matrix
301 * - string to use for s1
305 * - string to use for s2
307 * - substitution matrix to use for alignment
309 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
310 String string2, ScoreMatrix scoreMatrix)
314 setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
315 lookup = scoreMatrix.getMatrix();
319 * construct score matrix for string1 and string2 (after removing any existing
325 private void SeqInit(String string1, String string2)
327 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
328 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
330 if (s1str.length() == 0 || s2str.length() == 0)
332 output.append("ALL GAPS: "
333 + (s1str.length() == 0 ? s1.getName() : " ")
334 + (s2str.length() == 0 ? s2.getName() : ""));
338 // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
339 seq1 = new int[s1str.length()];
341 // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
342 seq2 = new int[s2str.length()];
344 // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
345 score = new int[s1str.length()][s2str.length()];
347 // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
348 E = new int[s1str.length()][s2str.length()];
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()];
354 // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
355 seq1 = stringToInt(s1str, type);
357 // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
358 seq2 = stringToInt(s2str, type);
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();
376 // tend = System.currentTimeMillis();
377 // System.out.println("Time take to traceback alignment = " + (tend-tstart)
381 private void setDefaultParams(String type)
385 if (type.equals(AlignSeq.PEP))
387 lookup = ResidueProperties.getDefaultPeptideMatrix();
389 else if (type.equals(AlignSeq.DNA))
391 lookup = ResidueProperties.getDefaultDnaMatrix();
395 private void setType(String type2)
398 if (type.equals(AlignSeq.PEP))
401 charToInt = ResidueProperties.aaIndex;
402 defInt = ResidueProperties.maxProteinIndex;
404 else if (type.equals(AlignSeq.DNA))
407 charToInt = ResidueProperties.nucleotideIndex;
408 defInt = ResidueProperties.maxNucleotideIndex;
412 output.append("Wrong type = dna or pep only");
413 throw new Error("Unknown Type " + type2
414 + " - dna or pep are the only allowed values.");
421 public void traceAlignment()
423 // Find the maximum score along the rhs or bottom row
426 for (int i = 0; i < seq1.length; i++)
428 if (score[i][seq2.length - 1] > max)
430 max = score[i][seq2.length - 1];
432 maxj = seq2.length - 1;
436 for (int j = 0; j < seq2.length; j++)
438 if (score[seq1.length - 1][j] > max)
440 max = score[seq1.length - 1][j];
441 maxi = seq1.length - 1;
446 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
450 maxscore = score[i][j] / 10;
455 aseq1 = new int[seq1.length + seq2.length];
456 aseq2 = new int[seq1.length + seq2.length];
458 count = (seq1.length + seq2.length) - 1;
460 while ((i > 0) && (j > 0))
462 if ((aseq1[count] != defInt) && (i >= 0))
464 aseq1[count] = seq1[i];
465 astr1 = s1str.charAt(i) + astr1;
468 if ((aseq2[count] != defInt) && (j > 0))
470 aseq2[count] = seq2[j];
471 astr2 = s2str.charAt(j) + astr2;
474 trace = findTrace(i, j);
484 aseq1[count] = defInt;
485 astr1 = "-" + astr1.substring(1);
487 else if (trace == -1)
490 aseq2[count] = defInt;
491 astr2 = "-" + astr2.substring(1);
500 if (aseq1[count] != defInt)
502 aseq1[count] = seq1[i];
503 astr1 = s1str.charAt(i) + astr1;
506 if (aseq2[count] != defInt)
508 aseq2[count] = seq2[j];
509 astr2 = s2str.charAt(j) + astr2;
516 public void printAlignment(java.io.PrintStream os)
518 // TODO: Use original sequence characters rather than re-translated
519 // characters in output
520 // Find the biggest id length for formatting purposes
521 String s1id = s1.getName(), s2id = s2.getName();
522 int maxid = s1.getName().length();
523 if (s2.getName().length() > maxid)
525 maxid = s2.getName().length();
530 // JAL-527 - truncate the sequence ids
531 if (s1.getName().length() > maxid)
533 s1id = s1.getName().substring(0, 30);
535 if (s2.getName().length() > maxid)
537 s2id = s2.getName().substring(0, 30);
540 int len = 72 - maxid - 1;
541 int nochunks = ((aseq1.length - count) / len) + 1;
544 output.append("Score = " + score[maxi][maxj] + "\n");
545 output.append("Length of alignment = " + (aseq1.length - count) + "\n");
546 output.append("Sequence ");
547 output.append(new Format("%" + maxid + "s").form(s1.getName()));
548 output.append(" : " + s1.getStart() + " - " + s1.getEnd()
549 + " (Sequence length = " + s1str.length() + ")\n");
550 output.append("Sequence ");
551 output.append(new Format("%" + maxid + "s").form(s2.getName()));
552 output.append(" : " + s2.getStart() + " - " + s2.getEnd()
553 + " (Sequence length = " + s2str.length() + ")\n\n");
555 for (int j = 0; j < nochunks; j++)
557 // Print the first aligned sequence
558 output.append(new Format("%" + (maxid) + "s").form(s1id) + " ");
560 for (int i = 0; i < len; i++)
562 if ((i + (j * len)) < astr1.length())
564 output.append(astr1.charAt(i + (j * len)));
569 output.append(new Format("%" + (maxid) + "s").form(" ") + " ");
571 // Print out the matching chars
572 for (int i = 0; i < len; i++)
574 if ((i + (j * len)) < astr1.length())
576 if (astr1.charAt(i + (j * len)) == astr2.charAt(i + (j * len))
577 && !jalview.util.Comparison.isGap(astr1.charAt(i
583 else if (type.equals("pep"))
585 if (ResidueProperties.getPAM250(astr1.charAt(i + (j * len)),
586 astr2.charAt(i + (j * len))) > 0)
602 // Now print the second aligned sequence
603 output = output.append("\n");
604 output = output.append(new Format("%" + (maxid) + "s").form(s2id)
607 for (int i = 0; i < len; i++)
609 if ((i + (j * len)) < astr2.length())
611 output.append(astr2.charAt(i + (j * len)));
615 output = output.append("\n\n");
618 pid = pid / (float) (aseq1.length - count) * 100;
619 output = output.append(new Format("Percentage ID = %2.2f\n\n")
624 os.print(output.toString());
625 } catch (Exception ex)
636 public void printScoreMatrix(int[][] mat)
641 for (int i = 0; i < n; i++)
643 // Print the top sequence
646 Format.print(System.out, "%8s", s2str.substring(0, 1));
648 for (int jj = 1; jj < m; jj++)
650 Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
653 System.out.println();
656 for (int j = 0; j < m; j++)
660 Format.print(System.out, "%3s", s1str.substring(i, i + 1));
663 Format.print(System.out, "%3d ", mat[i][j] / 10);
666 System.out.println();
678 * @return DOCUMENT ME!
680 public int findTrace(int i, int j)
683 int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
690 else if (F[i][j] == max)
704 else if (E[i][j] == max)
721 public void calcScoreMatrix()
726 // top left hand element
727 score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
728 E[0][0] = -gapExtend;
731 // Calculate the top row first
732 for (int j = 1; j < m; j++)
734 // What should these values be? 0 maybe
735 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
736 F[0][j] = -gapExtend;
738 score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
743 // Now do the left hand column
744 for (int i = 1; i < n; i++)
747 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
749 score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
750 traceback[i][0] = -1;
753 // Now do all the other rows
754 for (int i = 1; i < n; i++)
756 for (int j = 1; j < m; j++)
758 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
759 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
761 score[i][j] = max(score[i - 1][j - 1]
762 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
763 traceback[i][j] = findTrace(i, j);
776 * @return DOCUMENT ME!
778 public static String extractGaps(String gapChar, String seq)
780 StringTokenizer str = new StringTokenizer(seq, gapChar);
781 StringBuffer newString = new StringBuffer();
783 while (str.hasMoreTokens())
785 newString.append(str.nextToken());
788 return newString.toString();
801 * @return DOCUMENT ME!
803 public int max(int i1, int i2, int i3)
828 * @return DOCUMENT ME!
830 public int max(int i1, int i2)
850 * @return DOCUMENT ME!
852 public int[] stringToInt(String s, String type)
854 int[] seq1 = new int[s.length()];
856 for (int i = 0; i < s.length(); i++)
858 // String ss = s.substring(i, i + 1).toUpperCase();
859 char c = s.charAt(i);
860 if ('a' <= c && c <= 'z')
868 seq1[i] = charToInt[c]; // set accordingly from setType
869 if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
870 // peptides, or 4 for NA.
875 } catch (Exception e)
898 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
904 for (int i = 0; i < n; i++)
906 for (int j = 0; j < m; j++)
908 if (mat[i][j] >= max)
913 if (mat[i][j] <= min)
920 System.out.println(max + " " + min);
922 for (int i = 0; i < n; i++)
924 for (int j = 0; j < m; j++)
929 // System.out.println(mat[i][j]);
930 float score = (float) (mat[i][j] - min) / (float) (max - min);
931 g.setColor(new Color(score, 0, 0));
932 g.fillRect(x, y, psize, psize);
934 // System.out.println(x + " " + y + " " + score);
940 * Compute a globally optimal needleman and wunsch alignment between two
946 * AlignSeq.DNA or AlignSeq.PEP
948 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
951 AlignSeq as = new AlignSeq(s1, s2, type);
953 as.calcScoreMatrix();
960 * @return mapping from positions in S1 to corresponding positions in S2
962 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
964 ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
965 int pdbpos = s2.getStart() + getSeq2Start() - 2;
966 int alignpos = s1.getStart() + getSeq1Start() - 2;
967 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
968 boolean lastmatch = false;
969 // and now trace the alignment onto the atom set.
970 for (int i = 0; i < astr1.length(); i++)
972 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
983 if (allowmismatch || c1 == c2)
986 // extend mapping interval.
987 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
989 as1.add(Integer.valueOf(alignpos));
990 as2.add(Integer.valueOf(pdbpos));
1000 // construct range pairs
1001 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1002 .size() + (lastmatch ? 1 : 0)];
1004 for (Integer ip : as1)
1010 for (Integer ip : as2)
1017 mapseq1[mapseq1.length - 1] = alignpos;
1018 mapseq2[mapseq2.length - 1] = pdbpos;
1020 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1022 jalview.datamodel.Mapping mapping = new Mapping(map);
1028 * compute the PID vector used by the redundancy filter.
1030 * @param originalSequences
1031 * - sequences in alignment that are to filtered
1033 * - null or strings to be analysed (typically, visible portion of
1034 * each sequence in alignment)
1036 * - first column in window for calculation
1038 * - last column in window for calculation
1040 * - if true then use ungapped sequence to compute PID
1041 * @return vector containing maximum PID for i-th sequence and any sequences
1042 * longer than that seuqence
1044 public static float[] computeRedundancyMatrix(
1045 SequenceI[] originalSequences, String[] omitHidden, int start,
1046 int end, boolean ungapped)
1048 int height = originalSequences.length;
1049 float[] redundancy = new float[height];
1050 int[] lngth = new int[height];
1051 for (int i = 0; i < height; i++)
1057 // long start = System.currentTimeMillis();
1061 for (int i = 0; i < height; i++)
1064 for (int j = 0; j < i; j++)
1071 if (omitHidden == null)
1073 seqi = originalSequences[i].getSequenceAsString(start, end);
1074 seqj = originalSequences[j].getSequenceAsString(start, end);
1078 seqi = omitHidden[i];
1079 seqj = omitHidden[j];
1083 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1084 lngth[i] = ug.length();
1092 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1093 lngth[j] = ug.length();
1099 pid = Comparison.PID(seqi, seqj);
1101 // use real sequence length rather than string length
1102 if (lngth[j] < lngth[i])
1104 redundancy[j] = Math.max(pid, redundancy[j]);
1108 redundancy[i] = Math.max(pid, redundancy[i]);