2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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;
23 import java.awt.Color;
24 import java.awt.Graphics;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.List;
28 import java.util.StringTokenizer;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceI;
35 import jalview.schemes.ResidueProperties;
36 import jalview.schemes.ScoreMatrix;
37 import jalview.util.Comparison;
38 import jalview.util.Format;
39 import jalview.util.MapList;
40 import jalview.util.MessageManager;
50 public static final String PEP = "pep";
52 public static final String DNA = "dna";
54 private static final String NEWLINE = System.lineSeparator();
57 { "A", "C", "G", "T", "-" };
59 // "C", "T", "A", "G", "-"};
61 { "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F",
62 "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" };
92 public String astr1 = "";
94 public String astr2 = "";
103 public int seq2start;
121 int[][] lookup = ResidueProperties.getBLOSUM62();
123 String[] intToStr = pep;
127 StringBuffer output = new StringBuffer();
131 private int[] charToInt;
134 * Creates a new AlignSeq object.
143 public AlignSeq(SequenceI s1, SequenceI s2, String type)
145 SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
150 * Creates a new AlignSeq object.
159 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
160 String string2, String type)
162 SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
168 * @return DOCUMENT ME!
170 public int getMaxScore()
178 * @return DOCUMENT ME!
180 public int getSeq2Start()
188 * @return DOCUMENT ME!
190 public int getSeq2End()
198 * @return DOCUMENT ME!
200 public int getSeq1Start()
208 * @return DOCUMENT ME!
210 public int getSeq1End()
218 * @return DOCUMENT ME!
220 public String getOutput()
222 return output.toString();
228 * @return DOCUMENT ME!
230 public String getAStr1()
238 * @return DOCUMENT ME!
240 public String getAStr2()
248 * @return DOCUMENT ME!
250 public int[] getASeq1()
258 * @return DOCUMENT ME!
260 public int[] getASeq2()
268 * @return DOCUMENT ME!
270 public SequenceI getS1()
278 * @return DOCUMENT ME!
280 public SequenceI getS2()
287 * @return aligned instance of Seq 1
289 public SequenceI getAlignedSeq1()
291 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
292 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
293 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
294 alSeq1.setDatasetSequence(s1.getDatasetSequence() == null ? s1 : s1
295 .getDatasetSequence());
301 * @return aligned instance of Seq 2
303 public SequenceI getAlignedSeq2()
305 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
306 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
307 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
308 alSeq2.setDatasetSequence(s2.getDatasetSequence() == null ? s2 : s2
309 .getDatasetSequence());
314 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
319 * - string to use for s1
323 * - string to use for s2
327 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
328 String string2, String type)
332 setDefaultParams(type);
333 SeqInit(string1, string2);
337 * Construct score matrix for sequences with custom substitution matrix
342 * - string to use for s1
346 * - string to use for s2
348 * - substitution matrix to use for alignment
350 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
351 String string2, ScoreMatrix scoreMatrix)
355 setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
356 lookup = scoreMatrix.getMatrix();
360 * construct score matrix for string1 and string2 (after removing any existing
366 private void SeqInit(String string1, String string2)
368 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
369 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
371 if (s1str.length() == 0 || s2str.length() == 0)
373 output.append("ALL GAPS: "
374 + (s1str.length() == 0 ? s1.getName() : " ")
375 + (s2str.length() == 0 ? s2.getName() : ""));
379 // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
380 seq1 = new int[s1str.length()];
382 // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
383 seq2 = new int[s2str.length()];
385 // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
386 score = new int[s1str.length()][s2str.length()];
388 // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
389 E = new int[s1str.length()][s2str.length()];
391 // System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
392 F = new int[s1str.length()][s2str.length()];
393 traceback = new int[s1str.length()][s2str.length()];
395 // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
396 seq1 = stringToInt(s1str, type);
398 // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
399 seq2 = stringToInt(s2str, type);
401 // System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
402 // long tstart = System.currentTimeMillis();
403 // calcScoreMatrix();
404 // long tend = System.currentTimeMillis();
405 // System.out.println("Time take to calculate score matrix = " +
406 // (tend-tstart) + " ms");
407 // printScoreMatrix(score);
408 // System.out.println();
409 // printScoreMatrix(traceback);
410 // System.out.println();
411 // printScoreMatrix(E);
412 // System.out.println();
413 // /printScoreMatrix(F);
414 // System.out.println();
415 // tstart = System.currentTimeMillis();
417 // tend = System.currentTimeMillis();
418 // System.out.println("Time take to traceback alignment = " + (tend-tstart)
422 private void setDefaultParams(String type)
426 if (type.equals(AlignSeq.PEP))
428 lookup = ResidueProperties.getDefaultPeptideMatrix();
430 else if (type.equals(AlignSeq.DNA))
432 lookup = ResidueProperties.getDefaultDnaMatrix();
436 private void setType(String type2)
439 if (type.equals(AlignSeq.PEP))
442 charToInt = ResidueProperties.aaIndex;
443 defInt = ResidueProperties.maxProteinIndex;
445 else if (type.equals(AlignSeq.DNA))
448 charToInt = ResidueProperties.nucleotideIndex;
449 defInt = ResidueProperties.maxNucleotideIndex;
453 output.append("Wrong type = dna or pep only");
454 throw new Error(MessageManager.formatMessage("error.unknown_type_dna_or_pep", new String[]{type2}));
461 public void traceAlignment()
463 // Find the maximum score along the rhs or bottom row
466 for (int i = 0; i < seq1.length; i++)
468 if (score[i][seq2.length - 1] > max)
470 max = score[i][seq2.length - 1];
472 maxj = seq2.length - 1;
476 for (int j = 0; j < seq2.length; j++)
478 if (score[seq1.length - 1][j] > max)
480 max = score[seq1.length - 1][j];
481 maxi = seq1.length - 1;
486 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
490 maxscore = score[i][j] / 10;
495 aseq1 = new int[seq1.length + seq2.length];
496 aseq2 = new int[seq1.length + seq2.length];
498 count = (seq1.length + seq2.length) - 1;
500 while ((i > 0) && (j > 0))
502 if ((aseq1[count] != defInt) && (i >= 0))
504 aseq1[count] = seq1[i];
505 astr1 = s1str.charAt(i) + astr1;
508 if ((aseq2[count] != defInt) && (j > 0))
510 aseq2[count] = seq2[j];
511 astr2 = s2str.charAt(j) + astr2;
514 trace = findTrace(i, j);
524 aseq1[count] = defInt;
525 astr1 = "-" + astr1.substring(1);
527 else if (trace == -1)
530 aseq2[count] = defInt;
531 astr2 = "-" + astr2.substring(1);
540 if (aseq1[count] != defInt)
542 aseq1[count] = seq1[i];
543 astr1 = s1str.charAt(i) + astr1;
546 if (aseq2[count] != defInt)
548 aseq2[count] = seq2[j];
549 astr2 = s2str.charAt(j) + astr2;
556 public void printAlignment(java.io.PrintStream os)
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)
565 maxid = s2.getName().length();
570 // JAL-527 - truncate the sequence ids
571 if (s1.getName().length() > maxid)
573 s1id = s1.getName().substring(0, 30);
575 if (s2.getName().length() > maxid)
577 s2id = s2.getName().substring(0, 30);
580 int len = 72 - maxid - 1;
581 int nochunks = ((aseq1.length - count) / len) + 1;
584 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
585 output.append("Length of alignment = ")
586 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
587 output.append("Sequence ");
588 output.append(new Format("%" + maxid + "s").form(s1.getName()));
589 output.append(" : ").append(String.valueOf(s1.getStart()))
590 .append(" - ").append(String.valueOf(s1.getEnd()));
591 output.append(" (Sequence length = ")
592 .append(String.valueOf(s1str.length())).append(")")
594 output.append("Sequence ");
595 output.append(new Format("%" + maxid + "s").form(s2.getName()));
596 output.append(" : ").append(String.valueOf(s2.getStart()))
597 .append(" - ").append(String.valueOf(s2.getEnd()));
598 output.append(" (Sequence length = ")
599 .append(String.valueOf(s2str.length())).append(")")
600 .append(NEWLINE).append(NEWLINE);
602 for (int j = 0; j < nochunks; j++)
604 // Print the first aligned sequence
605 output.append(new Format("%" + (maxid) + "s").form(s1id)).append(" ");
607 for (int i = 0; i < len; i++)
609 if ((i + (j * len)) < astr1.length())
611 output.append(astr1.charAt(i + (j * len)));
615 output.append(NEWLINE);
616 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
618 // Print out the matching chars
619 for (int i = 0; i < len; i++)
621 if ((i + (j * len)) < astr1.length())
623 if (astr1.charAt(i + (j * len)) == astr2.charAt(i + (j * len))
624 && !jalview.util.Comparison.isGap(astr1.charAt(i
630 else if (type.equals("pep"))
632 if (ResidueProperties.getPAM250(astr1.charAt(i + (j * len)),
633 astr2.charAt(i + (j * len))) > 0)
649 // Now print the second aligned sequence
650 output = output.append(NEWLINE);
651 output = output.append(new Format("%" + (maxid) + "s").form(s2id))
654 for (int i = 0; i < len; i++)
656 if ((i + (j * len)) < astr2.length())
658 output.append(astr2.charAt(i + (j * len)));
662 output.append(NEWLINE).append(NEWLINE);
665 pid = pid / (aseq1.length - count) * 100;
666 output = output.append(new Format("Percentage ID = %2.2f\n\n")
671 os.print(output.toString());
672 } catch (Exception ex)
683 public void printScoreMatrix(int[][] mat)
688 for (int i = 0; i < n; i++)
690 // Print the top sequence
693 Format.print(System.out, "%8s", s2str.substring(0, 1));
695 for (int jj = 1; jj < m; jj++)
697 Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
700 System.out.println();
703 for (int j = 0; j < m; j++)
707 Format.print(System.out, "%3s", s1str.substring(i, i + 1));
710 Format.print(System.out, "%3d ", mat[i][j] / 10);
713 System.out.println();
725 * @return DOCUMENT ME!
727 public int findTrace(int i, int j)
730 int max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
737 else if (F[i][j] == max)
751 else if (E[i][j] == max)
768 public void calcScoreMatrix()
773 // top left hand element
774 score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
775 E[0][0] = -gapExtend;
778 // Calculate the top row first
779 for (int j = 1; j < m; j++)
781 // What should these values be? 0 maybe
782 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
783 F[0][j] = -gapExtend;
785 score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
790 // Now do the left hand column
791 for (int i = 1; i < n; i++)
794 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
796 score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
797 traceback[i][0] = -1;
800 // Now do all the other rows
801 for (int i = 1; i < n; i++)
803 for (int j = 1; j < m; j++)
805 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
806 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
808 score[i][j] = max(score[i - 1][j - 1]
809 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
810 traceback[i][j] = findTrace(i, j);
816 * Returns the given sequence with all of the given gap characters removed.
819 * a string of characters to be treated as gaps
825 public static String extractGaps(String gapChars, String seq)
827 if (gapChars == null || seq == null)
831 StringTokenizer str = new StringTokenizer(seq, gapChars);
832 StringBuilder newString = new StringBuilder(seq.length());
834 while (str.hasMoreTokens())
836 newString.append(str.nextToken());
839 return newString.toString();
852 * @return DOCUMENT ME!
854 public int max(int i1, int i2, int i3)
879 * @return DOCUMENT ME!
881 public int max(int i1, int i2)
901 * @return DOCUMENT ME!
903 public int[] stringToInt(String s, String type)
905 int[] seq1 = new int[s.length()];
907 for (int i = 0; i < s.length(); i++)
909 // String ss = s.substring(i, i + 1).toUpperCase();
910 char c = s.charAt(i);
911 if ('a' <= c && c <= 'z')
919 seq1[i] = charToInt[c]; // set accordingly from setType
920 if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
921 // peptides, or 4 for NA.
926 } catch (Exception e)
949 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
955 for (int i = 0; i < n; i++)
957 for (int j = 0; j < m; j++)
959 if (mat[i][j] >= max)
964 if (mat[i][j] <= min)
971 System.out.println(max + " " + min);
973 for (int i = 0; i < n; i++)
975 for (int j = 0; j < m; j++)
980 // System.out.println(mat[i][j]);
981 float score = (float) (mat[i][j] - min) / (float) (max - min);
982 g.setColor(new Color(score, 0, 0));
983 g.fillRect(x, y, psize, psize);
985 // System.out.println(x + " " + y + " " + score);
991 * Compute a globally optimal needleman and wunsch alignment between two
997 * AlignSeq.DNA or AlignSeq.PEP
999 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
1002 AlignSeq as = new AlignSeq(s1, s2, type);
1004 as.calcScoreMatrix();
1005 as.traceAlignment();
1011 * @return mapping from positions in S1 to corresponding positions in S2
1013 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
1015 ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
1016 int pdbpos = s2.getStart() + getSeq2Start() - 2;
1017 int alignpos = s1.getStart() + getSeq1Start() - 2;
1018 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
1019 boolean lastmatch = false;
1020 // and now trace the alignment onto the atom set.
1021 for (int i = 0; i < astr1.length(); i++)
1023 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
1034 if (allowmismatch || c1 == c2)
1036 // extend mapping interval
1037 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
1039 as1.add(Integer.valueOf(alignpos));
1040 as2.add(Integer.valueOf(pdbpos));
1048 // extend mapping interval
1051 as1.add(Integer.valueOf(lp1));
1052 as2.add(Integer.valueOf(lp2));
1057 // construct range pairs
1059 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1060 .size() + (lastmatch ? 1 : 0)];
1062 for (Integer ip : as1)
1068 for (Integer ip : as2)
1075 mapseq1[mapseq1.length - 1] = alignpos;
1076 mapseq2[mapseq2.length - 1] = pdbpos;
1078 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1080 jalview.datamodel.Mapping mapping = new Mapping(map);
1086 * matches ochains against al and populates seqs with the best match between
1087 * each ochain and the set in al
1091 * @param dnaOrProtein
1092 * @param removeOldAnnots
1093 * when true, old annotation is cleared before new annotation
1095 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
1096 * List<AlignSeq> alignment between each>
1098 public static List<List<? extends Object>> replaceMatchingSeqsWith(
1099 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
1100 List<SequenceI> ochains,
1101 AlignmentI al, String dnaOrProtein, boolean removeOldAnnots)
1103 List<SequenceI> orig = new ArrayList<SequenceI>(), repl = new ArrayList<SequenceI>();
1104 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
1105 if (al != null && al.getHeight() > 0)
1107 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1108 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1110 for (SequenceI sq : ochains)
1112 SequenceI bestm = null;
1113 AlignSeq bestaseq = null;
1115 for (SequenceI msq : al.getSequences())
1117 AlignSeq aseq = doGlobalNWAlignment(msq, sq,
1119 if (bestm == null || aseq.getMaxScore() > bestscore)
1121 bestscore = aseq.getMaxScore();
1126 System.out.println("Best Score for " + (matches.size() + 1) + " :"
1129 aligns.add(bestaseq);
1130 al.deleteSequence(bestm);
1132 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1134 SequenceI sq, sp = seqs.get(p);
1136 if ((q = ochains.indexOf(sp)) > -1)
1138 seqs.set(p, sq = matches.get(q));
1141 sq.setName(sp.getName());
1142 sq.setDescription(sp.getDescription());
1144 sq.transferAnnotation(sp, sp2sq = aligns.get(q).getMappingFromS1(false));
1145 aligs.add(aligns.get(q));
1147 for (int ap = 0; ap < annotations.size();)
1149 if (annotations.get(ap).sequenceRef == sp)
1155 if (removeOldAnnots) {
1156 annotations.remove(ap);
1158 AlignmentAnnotation alan = annotations.remove(ap);
1159 alan.liftOver(sq, sp2sq);
1160 alan.setSequenceRef(sq);
1161 sq.addAlignmentAnnotation(alan);
1169 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1171 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1172 Arrays.asList(sq.getAnnotation()));
1177 return Arrays.asList(orig, repl, aligs);
1181 * compute the PID vector used by the redundancy filter.
1183 * @param originalSequences
1184 * - sequences in alignment that are to filtered
1186 * - null or strings to be analysed (typically, visible portion of
1187 * each sequence in alignment)
1189 * - first column in window for calculation
1191 * - last column in window for calculation
1193 * - if true then use ungapped sequence to compute PID
1194 * @return vector containing maximum PID for i-th sequence and any sequences
1195 * longer than that seuqence
1197 public static float[] computeRedundancyMatrix(
1198 SequenceI[] originalSequences, String[] omitHidden, int start,
1199 int end, boolean ungapped)
1201 int height = originalSequences.length;
1202 float[] redundancy = new float[height];
1203 int[] lngth = new int[height];
1204 for (int i = 0; i < height; i++)
1210 // long start = System.currentTimeMillis();
1214 for (int i = 0; i < height; i++)
1217 for (int j = 0; j < i; j++)
1224 if (omitHidden == null)
1226 seqi = originalSequences[i].getSequenceAsString(start, end);
1227 seqj = originalSequences[j].getSequenceAsString(start, end);
1231 seqi = omitHidden[i];
1232 seqj = omitHidden[j];
1236 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1237 lngth[i] = ug.length();
1245 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1246 lngth[j] = ug.length();
1252 pid = Comparison.PID(seqi, seqj);
1254 // use real sequence length rather than string length
1255 if (lngth[j] < lngth[i])
1257 redundancy[j] = Math.max(pid, redundancy[j]);
1261 redundancy[i] = Math.max(pid, redundancy[i]);