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 = ScoreModels.getInstance().getBlosum62().getMatrix();
123 // ResidueProperties.getBLOSUM62();
125 String[] intToStr = pep;
129 StringBuffer output = new StringBuffer();
133 private int[] charToInt;
136 * Creates a new AlignSeq object.
145 public AlignSeq(SequenceI s1, SequenceI s2, String type)
147 SeqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
152 * Creates a new AlignSeq object.
161 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
162 String string2, String type)
164 SeqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
170 * @return DOCUMENT ME!
172 public float getMaxScore()
180 * @return DOCUMENT ME!
182 public int getSeq2Start()
190 * @return DOCUMENT ME!
192 public int getSeq2End()
200 * @return DOCUMENT ME!
202 public int getSeq1Start()
210 * @return DOCUMENT ME!
212 public int getSeq1End()
220 * @return DOCUMENT ME!
222 public String getOutput()
224 return output.toString();
230 * @return DOCUMENT ME!
232 public String getAStr1()
240 * @return DOCUMENT ME!
242 public String getAStr2()
250 * @return DOCUMENT ME!
252 public int[] getASeq1()
260 * @return DOCUMENT ME!
262 public int[] getASeq2()
270 * @return DOCUMENT ME!
272 public SequenceI getS1()
280 * @return DOCUMENT ME!
282 public SequenceI getS2()
289 * @return aligned instance of Seq 1
291 public SequenceI getAlignedSeq1()
293 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
294 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
295 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
296 alSeq1.setDatasetSequence(s1.getDatasetSequence() == null ? s1 : s1
297 .getDatasetSequence());
303 * @return aligned instance of Seq 2
305 public SequenceI getAlignedSeq2()
307 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
308 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
309 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
310 alSeq2.setDatasetSequence(s2.getDatasetSequence() == null ? s2 : s2
311 .getDatasetSequence());
316 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
321 * - string to use for s1
325 * - string to use for s2
329 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
330 String string2, String type)
334 setDefaultParams(type);
335 SeqInit(string1, string2);
339 * Construct score matrix for sequences with custom substitution matrix
344 * - string to use for s1
348 * - string to use for s2
350 * - substitution matrix to use for alignment
352 public void SeqInit(SequenceI s1, String string1, SequenceI s2,
353 String string2, ScoreMatrix scoreMatrix)
357 setType(scoreMatrix.isDNA() ? AlignSeq.DNA : AlignSeq.PEP);
358 lookup = scoreMatrix.getMatrix();
362 * construct score matrix for string1 and string2 (after removing any existing
368 private void SeqInit(String string1, String string2)
370 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
371 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
373 if (s1str.length() == 0 || s2str.length() == 0)
375 output.append("ALL GAPS: "
376 + (s1str.length() == 0 ? s1.getName() : " ")
377 + (s2str.length() == 0 ? s2.getName() : ""));
381 // System.out.println("lookuip " + rt.freeMemory() + " "+ rt.totalMemory());
382 seq1 = new int[s1str.length()];
384 // System.out.println("seq1 " + rt.freeMemory() +" " + rt.totalMemory());
385 seq2 = new int[s2str.length()];
387 // System.out.println("seq2 " + rt.freeMemory() + " " + rt.totalMemory());
388 score = new float[s1str.length()][s2str.length()];
390 // System.out.println("score " + rt.freeMemory() + " " + rt.totalMemory());
391 E = new float[s1str.length()][s2str.length()];
393 // System.out.println("E " + rt.freeMemory() + " " + rt.totalMemory());
394 F = new float[s1str.length()][s2str.length()];
395 traceback = new int[s1str.length()][s2str.length()];
397 // System.out.println("F " + rt.freeMemory() + " " + rt.totalMemory());
398 seq1 = stringToInt(s1str, type);
400 // System.out.println("seq1 " + rt.freeMemory() + " " + rt.totalMemory());
401 seq2 = stringToInt(s2str, type);
403 // System.out.println("Seq2 " + rt.freeMemory() + " " + rt.totalMemory());
404 // long tstart = System.currentTimeMillis();
405 // calcScoreMatrix();
406 // long tend = System.currentTimeMillis();
407 // System.out.println("Time take to calculate score matrix = " +
408 // (tend-tstart) + " ms");
409 // printScoreMatrix(score);
410 // System.out.println();
411 // printScoreMatrix(traceback);
412 // System.out.println();
413 // printScoreMatrix(E);
414 // System.out.println();
415 // /printScoreMatrix(F);
416 // System.out.println();
417 // tstart = System.currentTimeMillis();
419 // tend = System.currentTimeMillis();
420 // System.out.println("Time take to traceback alignment = " + (tend-tstart)
424 private void setDefaultParams(String type)
428 if (type.equals(AlignSeq.PEP))
430 lookup = ScoreModels.getInstance().getDefaultModel(true).getMatrix();
432 else if (type.equals(AlignSeq.DNA))
434 lookup = ScoreModels.getInstance().getDefaultModel(false).getMatrix();
438 private void setType(String type2)
441 if (type.equals(AlignSeq.PEP))
444 charToInt = ResidueProperties.aaIndex;
445 defInt = ResidueProperties.maxProteinIndex;
447 else if (type.equals(AlignSeq.DNA))
450 charToInt = ResidueProperties.nucleotideIndex;
451 defInt = ResidueProperties.maxNucleotideIndex;
455 output.append("Wrong type = dna or pep only");
456 throw new Error(MessageManager.formatMessage(
457 "error.unknown_type_dna_or_pep", new String[] { type2 }));
464 public void traceAlignment()
466 // Find the maximum score along the rhs or bottom row
469 for (int i = 0; i < seq1.length; i++)
471 if (score[i][seq2.length - 1] > max)
473 max = score[i][seq2.length - 1];
475 maxj = seq2.length - 1;
479 for (int j = 0; j < seq2.length; j++)
481 if (score[seq1.length - 1][j] > max)
483 max = score[seq1.length - 1][j];
484 maxi = seq1.length - 1;
489 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
493 maxscore = score[i][j] / 10;
498 aseq1 = new int[seq1.length + seq2.length];
499 aseq2 = new int[seq1.length + seq2.length];
501 count = (seq1.length + seq2.length) - 1;
503 while ((i > 0) && (j > 0))
505 if ((aseq1[count] != defInt) && (i >= 0))
507 aseq1[count] = seq1[i];
508 astr1 = s1str.charAt(i) + astr1;
511 if ((aseq2[count] != defInt) && (j > 0))
513 aseq2[count] = seq2[j];
514 astr2 = s2str.charAt(j) + astr2;
517 trace = findTrace(i, j);
527 aseq1[count] = defInt;
528 astr1 = "-" + astr1.substring(1);
530 else if (trace == -1)
533 aseq2[count] = defInt;
534 astr2 = "-" + astr2.substring(1);
543 if (aseq1[count] != defInt)
545 aseq1[count] = seq1[i];
546 astr1 = s1str.charAt(i) + astr1;
549 if (aseq2[count] != defInt)
551 aseq2[count] = seq2[j];
552 astr2 = s2str.charAt(j) + astr2;
559 public void printAlignment(java.io.PrintStream os)
561 // TODO: Use original sequence characters rather than re-translated
562 // characters in output
563 // Find the biggest id length for formatting purposes
564 String s1id = s1.getName(), s2id = s2.getName();
565 int maxid = s1.getName().length();
566 if (s2.getName().length() > maxid)
568 maxid = s2.getName().length();
573 // JAL-527 - truncate the sequence ids
574 if (s1.getName().length() > maxid)
576 s1id = s1.getName().substring(0, 30);
578 if (s2.getName().length() > maxid)
580 s2id = s2.getName().substring(0, 30);
583 int len = 72 - maxid - 1;
584 int nochunks = ((aseq1.length - count) / len)
585 + ((aseq1.length - count) % len > 0 ? 1 : 0);
588 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
589 output.append("Length of alignment = ")
590 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
591 output.append("Sequence ");
592 output.append(new Format("%" + maxid + "s").form(s1.getName()));
593 output.append(" : ").append(String.valueOf(s1.getStart()))
594 .append(" - ").append(String.valueOf(s1.getEnd()));
595 output.append(" (Sequence length = ")
596 .append(String.valueOf(s1str.length())).append(")")
598 output.append("Sequence ");
599 output.append(new Format("%" + maxid + "s").form(s2.getName()));
600 output.append(" : ").append(String.valueOf(s2.getStart()))
601 .append(" - ").append(String.valueOf(s2.getEnd()));
602 output.append(" (Sequence length = ")
603 .append(String.valueOf(s2str.length())).append(")")
604 .append(NEWLINE).append(NEWLINE);
606 PairwiseSeqScoreModel pam250 = ScoreModels.getInstance().getPam250();
608 for (int j = 0; j < nochunks; j++)
610 // Print the first aligned sequence
611 output.append(new Format("%" + (maxid) + "s").form(s1id)).append(" ");
613 for (int i = 0; i < len; i++)
615 if ((i + (j * len)) < astr1.length())
617 output.append(astr1.charAt(i + (j * len)));
621 output.append(NEWLINE);
622 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
625 * Print out the match symbols:
626 * | for exact match (ignoring case)
627 * . if PAM250 score is positive
630 for (int i = 0; i < len; i++)
632 if ((i + (j * len)) < astr1.length())
634 char c1 = astr1.charAt(i + (j * len));
635 char c2 = astr2.charAt(i + (j * len));
636 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
637 if (sameChar && !Comparison.isGap(c1))
642 else if (type.equals("pep"))
644 if (pam250.getPairwiseScore(c1, c2) > 0)
660 // Now print the second aligned sequence
661 output = output.append(NEWLINE);
662 output = output.append(new Format("%" + (maxid) + "s").form(s2id))
665 for (int i = 0; i < len; i++)
667 if ((i + (j * len)) < astr2.length())
669 output.append(astr2.charAt(i + (j * len)));
673 output.append(NEWLINE).append(NEWLINE);
676 pid = pid / (aseq1.length - count) * 100;
677 output = output.append(new Format("Percentage ID = %2.2f\n").form(pid));
680 os.print(output.toString());
681 } catch (Exception ex)
692 public void printScoreMatrix(int[][] mat)
697 for (int i = 0; i < n; i++)
699 // Print the top sequence
702 Format.print(System.out, "%8s", s2str.substring(0, 1));
704 for (int jj = 1; jj < m; jj++)
706 Format.print(System.out, "%5s", s2str.substring(jj, jj + 1));
709 System.out.println();
712 for (int j = 0; j < m; j++)
716 Format.print(System.out, "%3s", s1str.substring(i, i + 1));
719 Format.print(System.out, "%3d ", mat[i][j] / 10);
722 System.out.println();
734 * @return DOCUMENT ME!
736 public int findTrace(int i, int j)
739 float max = score[i - 1][j - 1] + (lookup[seq1[i]][seq2[j]] * 10);
746 else if (F[i][j] == max)
760 else if (E[i][j] == max)
777 public void calcScoreMatrix()
782 // top left hand element
783 score[0][0] = lookup[seq1[0]][seq2[0]] * 10;
784 E[0][0] = -gapExtend;
787 // Calculate the top row first
788 for (int j = 1; j < m; j++)
790 // What should these values be? 0 maybe
791 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
792 F[0][j] = -gapExtend;
794 score[0][j] = max(lookup[seq1[0]][seq2[j]] * 10, -gapOpen, -gapExtend);
799 // Now do the left hand column
800 for (int i = 1; i < n; i++)
803 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
805 score[i][0] = max(lookup[seq1[i]][seq2[0]] * 10, E[i][0], F[i][0]);
806 traceback[i][0] = -1;
809 // Now do all the other rows
810 for (int i = 1; i < n; i++)
812 for (int j = 1; j < m; j++)
814 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
815 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
817 score[i][j] = max(score[i - 1][j - 1]
818 + (lookup[seq1[i]][seq2[j]] * 10), E[i][j], F[i][j]);
819 traceback[i][j] = findTrace(i, j);
825 * Returns the given sequence with all of the given gap characters removed.
828 * a string of characters to be treated as gaps
834 public static String extractGaps(String gapChars, String seq)
836 if (gapChars == null || seq == null)
840 StringTokenizer str = new StringTokenizer(seq, gapChars);
841 StringBuilder newString = new StringBuilder(seq.length());
843 while (str.hasMoreTokens())
845 newString.append(str.nextToken());
848 return newString.toString();
861 * @return DOCUMENT ME!
863 public float max(float f1, float f2, float f3)
888 * @return DOCUMENT ME!
890 public float max(float f1, float f2)
910 * @return DOCUMENT ME!
912 public int[] stringToInt(String s, String type)
914 int[] seq1 = new int[s.length()];
916 for (int i = 0; i < s.length(); i++)
918 // String ss = s.substring(i, i + 1).toUpperCase();
919 char c = s.charAt(i);
920 if ('a' <= c && c <= 'z')
928 seq1[i] = charToInt[c]; // set accordingly from setType
929 if (seq1[i] < 0 || seq1[i] > defInt) // set from setType: 23 for
930 // peptides, or 4 for NA.
935 } catch (Exception e)
958 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
961 // TODO method dosen't seem to be referenced anywhere delete??
965 for (int i = 0; i < n; i++)
967 for (int j = 0; j < m; j++)
969 if (mat[i][j] >= max)
974 if (mat[i][j] <= min)
981 System.out.println(max + " " + min);
983 for (int i = 0; i < n; i++)
985 for (int j = 0; j < m; j++)
990 // System.out.println(mat[i][j]);
991 float score = (float) (mat[i][j] - min) / (float) (max - min);
992 g.setColor(new Color(score, 0, 0));
993 g.fillRect(x, y, psize, psize);
995 // System.out.println(x + " " + y + " " + score);
1001 * Compute a globally optimal needleman and wunsch alignment between two
1007 * AlignSeq.DNA or AlignSeq.PEP
1009 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
1012 AlignSeq as = new AlignSeq(s1, s2, type);
1014 as.calcScoreMatrix();
1015 as.traceAlignment();
1021 * @return mapping from positions in S1 to corresponding positions in S2
1023 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
1025 ArrayList<Integer> as1 = new ArrayList<Integer>(), as2 = new ArrayList<Integer>();
1026 int pdbpos = s2.getStart() + getSeq2Start() - 2;
1027 int alignpos = s1.getStart() + getSeq1Start() - 2;
1028 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
1029 boolean lastmatch = false;
1030 // and now trace the alignment onto the atom set.
1031 for (int i = 0; i < astr1.length(); i++)
1033 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
1044 if (allowmismatch || c1 == c2)
1046 // extend mapping interval
1047 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
1049 as1.add(Integer.valueOf(alignpos));
1050 as2.add(Integer.valueOf(pdbpos));
1058 // extend mapping interval
1061 as1.add(Integer.valueOf(lp1));
1062 as2.add(Integer.valueOf(lp2));
1067 // construct range pairs
1069 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)], mapseq2 = new int[as2
1070 .size() + (lastmatch ? 1 : 0)];
1072 for (Integer ip : as1)
1078 for (Integer ip : as2)
1085 mapseq1[mapseq1.length - 1] = alignpos;
1086 mapseq2[mapseq2.length - 1] = pdbpos;
1088 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
1090 jalview.datamodel.Mapping mapping = new Mapping(map);
1096 * matches ochains against al and populates seqs with the best match between
1097 * each ochain and the set in al
1101 * @param dnaOrProtein
1102 * @param removeOldAnnots
1103 * when true, old annotation is cleared before new annotation
1105 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
1106 * List<AlignSeq> alignment between each>
1108 public static List<List<? extends Object>> replaceMatchingSeqsWith(
1109 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
1110 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
1111 boolean removeOldAnnots)
1113 List<SequenceI> orig = new ArrayList<SequenceI>(), repl = new ArrayList<SequenceI>();
1114 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
1115 if (al != null && al.getHeight() > 0)
1117 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1118 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1120 for (SequenceI sq : ochains)
1122 SequenceI bestm = null;
1123 AlignSeq bestaseq = null;
1124 float bestscore = 0;
1125 for (SequenceI msq : al.getSequences())
1127 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
1128 if (bestm == null || aseq.getMaxScore() > bestscore)
1130 bestscore = aseq.getMaxScore();
1135 System.out.println("Best Score for " + (matches.size() + 1) + " :"
1138 aligns.add(bestaseq);
1139 al.deleteSequence(bestm);
1141 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1143 SequenceI sq, sp = seqs.get(p);
1145 if ((q = ochains.indexOf(sp)) > -1)
1147 seqs.set(p, sq = matches.get(q));
1150 sq.setName(sp.getName());
1151 sq.setDescription(sp.getDescription());
1153 sq.transferAnnotation(sp,
1154 sp2sq = aligns.get(q).getMappingFromS1(false));
1155 aligs.add(aligns.get(q));
1157 for (int ap = 0; ap < annotations.size();)
1159 if (annotations.get(ap).sequenceRef == sp)
1165 if (removeOldAnnots)
1167 annotations.remove(ap);
1171 AlignmentAnnotation alan = annotations.remove(ap);
1172 alan.liftOver(sq, sp2sq);
1173 alan.setSequenceRef(sq);
1174 sq.addAlignmentAnnotation(alan);
1182 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1184 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1185 Arrays.asList(sq.getAnnotation()));
1190 return Arrays.asList(orig, repl, aligs);
1194 * compute the PID vector used by the redundancy filter.
1196 * @param originalSequences
1197 * - sequences in alignment that are to filtered
1199 * - null or strings to be analysed (typically, visible portion of
1200 * each sequence in alignment)
1202 * - first column in window for calculation
1204 * - last column in window for calculation
1206 * - if true then use ungapped sequence to compute PID
1207 * @return vector containing maximum PID for i-th sequence and any sequences
1208 * longer than that seuqence
1210 public static float[] computeRedundancyMatrix(
1211 SequenceI[] originalSequences, String[] omitHidden, int start,
1212 int end, boolean ungapped)
1214 int height = originalSequences.length;
1215 float[] redundancy = new float[height];
1216 int[] lngth = new int[height];
1217 for (int i = 0; i < height; i++)
1223 // long start = System.currentTimeMillis();
1227 for (int i = 0; i < height; i++)
1230 for (int j = 0; j < i; j++)
1237 if (omitHidden == null)
1239 seqi = originalSequences[i].getSequenceAsString(start, end);
1240 seqj = originalSequences[j].getSequenceAsString(start, end);
1244 seqi = omitHidden[i];
1245 seqj = omitHidden[j];
1249 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1250 lngth[i] = ug.length();
1258 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1259 lngth[j] = ug.length();
1265 pid = Comparison.PID(seqi, seqj);
1267 // use real sequence length rather than string length
1268 if (lngth[j] < lngth[i])
1270 redundancy[j] = Math.max(pid, redundancy[j]);
1274 redundancy[i] = Math.max(pid, redundancy[i]);