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 jalview.analysis.scoremodels.PairwiseSeqScoreModel;
24 import jalview.analysis.scoremodels.ScoreMatrix;
25 import jalview.analysis.scoremodels.ScoreModels;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceI;
31 import jalview.schemes.ResidueProperties;
32 import jalview.util.Comparison;
33 import jalview.util.Format;
34 import jalview.util.MapList;
35 import jalview.util.MessageManager;
37 import java.awt.Color;
38 import java.awt.Graphics;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.List;
42 import java.util.StringTokenizer;
52 public static final String PEP = "pep";
54 public static final String DNA = "dna";
56 private static final String NEWLINE = System.lineSeparator();
58 static String[] dna = { "A", "C", "G", "T", "-" };
60 // "C", "T", "A", "G", "-"};
61 static String[] pep = { "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I",
62 "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V", "B", "Z", "X", "-" };
92 public String astr1 = "";
94 public String astr2 = "";
103 public int seq2start;
111 public float maxscore;
121 float[][] lookup = ((ScoreMatrix) ScoreModels.getInstance().forName(
122 ScoreModels.BLOSUM62)).getMatrix();
124 // ResidueProperties.getBLOSUM62();
126 String[] intToStr = pep;
130 StringBuffer output = new StringBuffer();
134 private int[] charToInt;
137 * Creates a new AlignSeq object.
146 public AlignSeq(SequenceI s1, SequenceI s2, String type)
148 SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
153 * Creates a new AlignSeq object.
162 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
163 String string2, String type)
165 SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
171 * @return DOCUMENT ME!
173 public float getMaxScore()
181 * @return DOCUMENT ME!
183 public int getSeq2Start()
191 * @return DOCUMENT ME!
193 public int getSeq2End()
201 * @return DOCUMENT ME!
203 public int getSeq1Start()
211 * @return DOCUMENT ME!
213 public int getSeq1End()
221 * @return DOCUMENT ME!
223 public String getOutput()
225 return output.toString();
231 * @return DOCUMENT ME!
233 public String getAStr1()
241 * @return DOCUMENT ME!
243 public String getAStr2()
251 * @return DOCUMENT ME!
253 public int[] getASeq1()
261 * @return DOCUMENT ME!
263 public int[] getASeq2()
271 * @return DOCUMENT ME!
273 public SequenceI getS1()
281 * @return DOCUMENT ME!
283 public SequenceI getS2()
290 * @return aligned instance of Seq 1
292 public SequenceI getAlignedSeq1()
294 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
295 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
296 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
297 alSeq1.setDatasetSequence(s1.getDatasetSequence() == null ? s1 : s1
298 .getDatasetSequence());
304 * @return aligned instance of Seq 2
306 public SequenceI getAlignedSeq2()
308 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
309 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
310 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
311 alSeq2.setDatasetSequence(s2.getDatasetSequence() == null ? s2 : s2
312 .getDatasetSequence());
317 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
322 * - string to use for s1
326 * - string to use for s2
330 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
331 String string2, String type)
335 setDefaultParams(type);
336 SeqInit(string1, string2);
340 * Construct score matrix for sequences with custom substitution matrix
345 * - string to use for s1
349 * - string to use for s2
351 * - substitution matrix to use for alignment
353 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
354 String string2, ScoreMatrix scoreMatrix)
358 setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
359 lookup = scoreMatrix.getMatrix();
363 * construct score matrix for string1 and string2 (after removing any existing
369 private void SeqInit(String string1, String string2)
371 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
372 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
374 if (s1str.length() == 0 || s2str.length() == 0)
376 output.append("ALL GAPS: "
377 + (s1str.length() == 0 ? s1.getName() : " ")
378 + (s2str.length() == 0 ? s2.getName() : ""));
382 // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
383 seq1 = new int[s1str.length()];
385 // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
386 seq2 = new int[s2str.length()];
388 // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
389 score = new float[s1str.length()][s2str.length()];
391 // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
392 E = new float[s1str.length()][s2str.length()];
394 // System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
395 F = new float[s1str.length()][s2str.length()];
396 traceback = new int[s1str.length()][s2str.length()];
398 // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
399 seq1 = stringToInt(s1str, type);
401 // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
402 seq2 = stringToInt(s2str, type);
404 // System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
405 // long tstart = System.currentTimeMillis();
406 // calcScoreMatrix();
407 // long tend = System.currentTimeMillis();
408 // System.out.println("Time take to calculate score matrix = " +
409 // (tend-tstart) + " ms");
410 // printScoreMatrix(score);
411 // System.out.println();
412 // printScoreMatrix(traceback);
413 // System.out.println();
414 // printScoreMatrix(E);
415 // System.out.println();
416 // /printScoreMatrix(F);
417 // System.out.println();
418 // tstart = System.currentTimeMillis();
420 // tend = System.currentTimeMillis();
421 // System.out.println("Time take to traceback alignment = " + (tend-tstart)
425 private void setDefaultParams(String type)
429 if (type.equals(AlignSeq.PEP))
431 lookup = ScoreModels.getInstance().getDefaultModel(true).getMatrix();
433 else if (type.equals(AlignSeq.DNA))
435 lookup = ScoreModels.getInstance().getDefaultModel(false).getMatrix();
439 private void setType(String type2)
442 if (type.equals(AlignSeq.PEP))
445 charToInt = ResidueProperties.aaIndex;
446 defInt = ResidueProperties.maxProteinIndex;
448 else if (type.equals(AlignSeq.DNA))
451 charToInt = ResidueProperties.nucleotideIndex;
452 defInt = ResidueProperties.maxNucleotideIndex;
456 output.append("Wrong type = dna or pep only");
457 throw new Error(MessageManager.formatMessage(
458 "error.unknown_type_dna_or_pep", new String[] { type2 }));
465 public void traceAlignment()
467 // Find the maximum score along the rhs or bottom row
470 for (int i = 0; i < seq1.length; i++)
472 if (score[i][seq2.length - 1] > max)
474 max = score[i][seq2.length - 1];
476 maxj = seq2.length - 1;
480 for (int j = 0; j < seq2.length; j++)
482 if (score[seq1.length - 1][j] > max)
484 max = score[seq1.length - 1][j];
485 maxi = seq1.length - 1;
490 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
494 maxscore = score[i][j] / 10;
499 aseq1 = new int[seq1.length + seq2.length];
500 aseq2 = new int[seq1.length + seq2.length];
502 count = (seq1.length + seq2.length) - 1;
504 while ((i > 0) && (j > 0))
506 if ((aseq1[count] != defInt) && (i >= 0))
508 aseq1[count] = seq1[i];
509 astr1 = s1str.charAt(i) + astr1;
512 if ((aseq2[count] != defInt) && (j > 0))
514 aseq2[count] = seq2[j];
515 astr2 = s2str.charAt(j) + astr2;
518 trace = findTrace(i, j);
528 aseq1[count] = defInt;
529 astr1 = "-" + astr1.substring(1);
531 else if (trace == -1)
534 aseq2[count] = defInt;
535 astr2 = "-" + astr2.substring(1);
544 if (aseq1[count] != defInt)
546 aseq1[count] = seq1[i];
547 astr1 = s1str.charAt(i) + astr1;
550 if (aseq2[count] != defInt)
552 aseq2[count] = seq2[j];
553 astr2 = s2str.charAt(j) + astr2;
560 public void printAlignment(java.io.PrintStream os)
562 // TODO: Use original sequence characters rather than re-translated
563 // characters in output
564 // Find the biggest id length for formatting purposes
565 String s1id = s1.getName(), s2id = s2.getName();
566 int maxid = s1.getName().length();
567 if (s2.getName().length() > maxid)
569 maxid = s2.getName().length();
574 // JAL-527 - truncate the sequence ids
575 if (s1.getName().length() > maxid)
577 s1id = s1.getName().substring(0, 30);
579 if (s2.getName().length() > maxid)
581 s2id = s2.getName().substring(0, 30);
584 int len = 72 - maxid - 1;
585 int nochunks = ((aseq1.length - count) / len)
586 + ((aseq1.length - count) % len > 0 ? 1 : 0);
589 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
590 output.append("Length of alignment = ")
591 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
592 output.append("Sequence ");
593 output.append(new Format("%" + maxid + "s").form(s1.getName()));
594 output.append(" : ").append(String.valueOf(s1.getStart()))
595 .append(" - ").append(String.valueOf(s1.getEnd()));
596 output.append(" (Sequence length = ")
597 .append(String.valueOf(s1str.length())).append(")")
599 output.append("Sequence ");
600 output.append(new Format("%" + maxid + "s").form(s2.getName()));
601 output.append(" : ").append(String.valueOf(s2.getStart()))
602 .append(" - ").append(String.valueOf(s2.getEnd()));
603 output.append(" (Sequence length = ")
604 .append(String.valueOf(s2str.length())).append(")")
605 .append(NEWLINE).append(NEWLINE);
607 PairwiseSeqScoreModel pam250 = (PairwiseSeqScoreModel) ScoreModels
608 .getInstance().forName(ScoreModels.PAM250);
610 for (int j = 0; j < nochunks; j++)
612 // Print the first aligned sequence
613 output.append(new Format("%" + (maxid) + "s").form(s1id)).append(" ");
615 for (int i = 0; i < len; i++)
617 if ((i + (j * len)) < astr1.length())
619 output.append(astr1.charAt(i + (j * len)));
623 output.append(NEWLINE);
624 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
627 * Print out the match symbols:
628 * | for exact match (ignoring case)
629 * . if PAM250 score is positive
632 for (int i = 0; i < len; i++)
634 if ((i + (j * len)) < astr1.length())
636 char c1 = astr1.charAt(i + (j * len));
637 char c2 = astr2.charAt(i + (j * len));
638 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
639 if (sameChar && !Comparison.isGap(c1))
644 else if (type.equals("pep"))
646 if (pam250.getPairwiseScore(c1, c2) > 0)
662 // Now print the second aligned sequence
663 output = output.append(NEWLINE);
664 output = output.append(new Format("%" + (maxid) + "s").form(s2id))
667 for (int i = 0; i < len; i++)
669 if ((i + (j * len)) < astr2.length())
671 output.append(astr2.charAt(i + (j * len)));
675 output.append(NEWLINE).append(NEWLINE);
678 pid = pid / (aseq1.length - count) * 100;
679 output = output.append(new Format("Percentage ID = %2.2f\n").form(pid));
682 os.print(output.toString());
683 } catch (Exception ex)
694 public void printScoreMatrix(int[][] mat)
699 for (int i = 0; i < n; i++)
701 // Print the top sequence
704 Format.print(System.out, "%8s", s2str.substring(0, 1));
706 for (int jj = 1; jj < m; jj++)
708 Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
711 System.out.println();
714 for (int j = 0; j < m; j++)
718 Format.print(System.out, "%3s", s1str.substring(i, i + 1));
721 Format.print(System.out, "%3d ", mat[i][j] / 10);
724 System.out.println();
736 * @return DOCUMENT ME!
738 public int findTrace(int i, int j)
741 float max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
748 else if (F[i][j] == max)
762 else if (E[i][j] == max)
779 public void calcScoreMatrix()
784 // top left hand element
785 score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
786 E[0][0] = -gapExtend;
789 // Calculate the top row first
790 for (int j = 1; j < m; j++)
792 // What should these values be? 0 maybe
793 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
794 F[0][j] = -gapExtend;
796 score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
801 // Now do the left hand column
802 for (int i = 1; i < n; i++)
805 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
807 score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
808 traceback[i][0] = -1;
811 // Now do all the other rows
812 for (int i = 1; i < n; i++)
814 for (int j = 1; j < m; j++)
816 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
817 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
819 score[i][j] = max(score[i - 1][j - 1]
820 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
821 traceback[i][j] = findTrace(i, j);
827 * Returns the given sequence with all of the given gap characters removed.
830 * a string of characters to be treated as gaps
836 public static String extractGaps(String gapChars, String seq)
838 if (gapChars == null || seq == null)
842 StringTokenizer str = new StringTokenizer(seq, gapChars);
843 StringBuilder newString = new StringBuilder(seq.length());
845 while (str.hasMoreTokens())
847 newString.append(str.nextToken());
850 return newString.toString();
863 * @return DOCUMENT ME!
865 public float max(float f1, float f2, float f3)
890 * @return DOCUMENT ME!
892 public float max(float f1, float f2)
912 * @return DOCUMENT ME!
914 public int[] stringToInt(String s, String type)
916 int[] seq1 = new int[s.length()];
918 for (int i = 0; i < s.length(); i++)
920 // String ss = s.substring(i, i + 1).toUpperCase();
921 char c = s.charAt(i);
922 if ('a' <= c && c <= 'z')
930 seq1[i] = charToInt[c]; // set accordingly from setType
931 if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
932 // peptides, or 4 for NA.
937 } catch (Exception e)
960 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
963 // TODO method dosen't seem to be referenced anywhere delete??
967 for (int i = 0; i < n; i++)
969 for (int j = 0; j < m; j++)
971 if (mat[i][j] >= max)
976 if (mat[i][j] <= min)
983 System.out.println(max + " " + min);
985 for (int i = 0; i < n; i++)
987 for (int j = 0; j < m; j++)
992 // System.out.println(mat[i][j]);
993 float score = (float) (mat[i][j] - min) / (float) (max - min);
994 g.setColor(new Color(score, 0, 0));
995 g.fillRect(x, y, psize, psize);
997 // System.out.println(x + " " + y + " " + score);
1003 * Compute a globally optimal needleman and wunsch alignment between two
1009 * AlignSeq.DNA or AlignSeq.PEP
1011 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
1014 AlignSeq as = new AlignSeq(s1, s2, type);
1016 as.calcScoreMatrix();
1017 as.traceAlignment();
1023 * @return mapping from positions in S1 to corresponding positions in S2
1025 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
1027 ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
1028 int pdbpos = s2.getStart() + getSeq2Start() - 2;
1029 int alignpos = s1.getStart() + getSeq1Start() - 2;
1030 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
1031 boolean lastmatch = false;
1032 // and now trace the alignment onto the atom set.
1033 for (int i = 0; i < astr1.length(); i++)
1035 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
1046 if (allowmismatch || c1 == c2)
1048 // extend mapping interval
1049 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
1051 as1.add(Integer.valueOf(alignpos));
1052 as2.add(Integer.valueOf(pdbpos));
1060 // extend mapping interval
1063 as1.add(Integer.valueOf(lp1));
1064 as2.add(Integer.valueOf(lp2));
1069 // construct range pairs
1071 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1072 .size() + (lastmatch ? 1 : 0)];
1074 for (Integer ip : as1)
1080 for (Integer ip : as2)
1087 mapseq1[mapseq1.length - 1] = alignpos;
1088 mapseq2[mapseq2.length - 1] = pdbpos;
1090 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1092 jalview.datamodel.Mapping mapping = new Mapping(map);
1098 * matches ochains against al and populates seqs with the best match between
1099 * each ochain and the set in al
1103 * @param dnaOrProtein
1104 * @param removeOldAnnots
1105 * when true, old annotation is cleared before new annotation
1107 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
1108 * List<AlignSeq> alignment between each>
1110 public static List<List<? extends Object>> replaceMatchingSeqsWith(
1111 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
1112 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
1113 boolean removeOldAnnots)
1115 List<SequenceI> orig = new ArrayList<SequenceI>(), repl = new ArrayList<SequenceI>();
1116 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
1117 if (al != null && al.getHeight() > 0)
1119 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1120 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1122 for (SequenceI sq : ochains)
1124 SequenceI bestm = null;
1125 AlignSeq bestaseq = null;
1126 float bestscore = 0;
1127 for (SequenceI msq : al.getSequences())
1129 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
1130 if (bestm == null || aseq.getMaxScore() > bestscore)
1132 bestscore = aseq.getMaxScore();
1137 System.out.println("Best Score for " + (matches.size() + 1) + " :"
1140 aligns.add(bestaseq);
1141 al.deleteSequence(bestm);
1143 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1145 SequenceI sq, sp = seqs.get(p);
1147 if ((q = ochains.indexOf(sp)) > -1)
1149 seqs.set(p, sq = matches.get(q));
1152 sq.setName(sp.getName());
1153 sq.setDescription(sp.getDescription());
1155 sq.transferAnnotation(sp,
1156 sp2sq = aligns.get(q).getMappingFromS1(false));
1157 aligs.add(aligns.get(q));
1159 for (int ap = 0; ap < annotations.size();)
1161 if (annotations.get(ap).sequenceRef == sp)
1167 if (removeOldAnnots)
1169 annotations.remove(ap);
1173 AlignmentAnnotation alan = annotations.remove(ap);
1174 alan.liftOver(sq, sp2sq);
1175 alan.setSequenceRef(sq);
1176 sq.addAlignmentAnnotation(alan);
1184 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1186 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1187 Arrays.asList(sq.getAnnotation()));
1192 return Arrays.asList(orig, repl, aligs);
1196 * compute the PID vector used by the redundancy filter.
1198 * @param originalSequences
1199 * - sequences in alignment that are to filtered
1201 * - null or strings to be analysed (typically, visible portion of
1202 * each sequence in alignment)
1204 * - first column in window for calculation
1206 * - last column in window for calculation
1208 * - if true then use ungapped sequence to compute PID
1209 * @return vector containing maximum PID for i-th sequence and any sequences
1210 * longer than that seuqence
1212 public static float[] computeRedundancyMatrix(
1213 SequenceI[] originalSequences, String[] omitHidden, int start,
1214 int end, boolean ungapped)
1216 int height = originalSequences.length;
1217 float[] redundancy = new float[height];
1218 int[] lngth = new int[height];
1219 for (int i = 0; i < height; i++)
1225 // long start = System.currentTimeMillis();
1229 for (int i = 0; i < height; i++)
1232 for (int j = 0; j < i; j++)
1239 if (omitHidden == null)
1241 seqi = originalSequences[i].getSequenceAsString(start, end);
1242 seqj = originalSequences[j].getSequenceAsString(start, end);
1246 seqi = omitHidden[i];
1247 seqj = omitHidden[j];
1251 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1252 lngth[i] = ug.length();
1260 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1261 lngth[j] = ug.length();
1267 pid = Comparison.PID(seqi, seqj);
1269 // use real sequence length rather than string length
1270 if (lngth[j] < lngth[i])
1272 redundancy[j] = Math.max(pid, redundancy[j]);
1276 redundancy[i] = Math.max(pid, redundancy[i]);