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.util.Locale;
25 import jalview.analysis.scoremodels.PIDModel;
26 import jalview.analysis.scoremodels.ScoreMatrix;
27 import jalview.analysis.scoremodels.ScoreModels;
28 import jalview.analysis.scoremodels.SimilarityParams;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.Mapping;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceI;
34 import jalview.util.Comparison;
35 import jalview.util.Format;
36 import jalview.util.MapList;
37 import jalview.util.MessageManager;
39 import java.awt.Color;
40 import java.awt.Graphics;
41 import java.io.PrintStream;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.List;
45 import java.util.StringTokenizer;
55 private static final int MAX_NAME_LENGTH = 30;
57 private static final int GAP_OPEN_COST = 120;
59 private static final int GAP_EXTEND_COST = 20;
61 private static final int GAP_INDEX = -1;
63 public static final String PEP = "pep";
65 public static final String DNA = "dna";
67 private static final String NEWLINE = System.lineSeparator();
75 int[][] traceback; // todo is this actually used?
98 * matches in alignment
102 public String astr1 = "";
104 public String astr2 = "";
107 public int seq1start;
113 public int seq2start;
119 public float maxscore;
123 StringBuffer output = new StringBuffer();
125 String type; // AlignSeq.PEP or AlignSeq.DNA
127 private ScoreMatrix scoreMatrix;
130 * Creates a new AlignSeq object.
133 * first sequence for alignment
135 * second sequence for alignment
137 * molecule type, either AlignSeq.PEP or AlignSeq.DNA
139 public AlignSeq(SequenceI s1, SequenceI s2, String type)
141 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
146 * Creates a new AlignSeq object.
155 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
156 String string2, String type)
158 seqInit(s1, string1.toUpperCase(Locale.ROOT), s2,
159 string2.toUpperCase(Locale.ROOT), type);
165 * @return DOCUMENT ME!
167 public float getMaxScore()
175 * @return DOCUMENT ME!
177 public int getSeq2Start()
185 * @return DOCUMENT ME!
187 public int getSeq2End()
195 * @return DOCUMENT ME!
197 public int getSeq1Start()
205 * @return DOCUMENT ME!
207 public int getSeq1End()
215 * @return DOCUMENT ME!
217 public String getOutput()
219 return output.toString();
225 * @return DOCUMENT ME!
227 public String getAStr1()
235 * @return DOCUMENT ME!
237 public String getAStr2()
245 * @return DOCUMENT ME!
247 public int[] getASeq1()
255 * @return DOCUMENT ME!
257 public int[] getASeq2()
264 * @return aligned instance of Seq 1
266 public SequenceI getAlignedSeq1()
268 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
269 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
270 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
271 alSeq1.setDatasetSequence(
272 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
278 * @return aligned instance of Seq 2
280 public SequenceI getAlignedSeq2()
282 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
283 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
284 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
285 alSeq2.setDatasetSequence(
286 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
290 * fraction of seq2 matched in the alignment
291 * @return NaN or [0..1]
293 public double getS2Coverage()
297 return ((double)match)/((double)s2.getEnd()-s2.getStart()+1);
302 * fraction of seq1 matched in the alignment
303 * @return NaN or [0..1]
305 public double getS1Coverage()
309 return ((double)match)/((double)s1.getEnd()-s1.getStart()+1);
315 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
320 * - string to use for s1
324 * - string to use for s2
328 public void seqInit(SequenceI s1, String string1, SequenceI s2,
329 String string2, String type)
333 setDefaultParams(type);
334 seqInit(string1, string2);
338 * construct score matrix for string1 and string2 (after removing any existing
344 private void seqInit(String string1, String string2)
346 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
347 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
349 if (s1str.length() == 0 || s2str.length() == 0)
352 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
353 + (s2str.length() == 0 ? s2.getName() : ""));
357 score = new float[s1str.length()][s2str.length()];
359 E = new float[s1str.length()][s2str.length()];
361 F = new float[s1str.length()][s2str.length()];
362 traceback = new int[s1str.length()][s2str.length()];
364 seq1 = indexEncode(s1str);
366 seq2 = indexEncode(s2str);
369 private void setDefaultParams(String moleculeType)
371 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
373 output.append("Wrong type = dna or pep only");
374 throw new Error(MessageManager
375 .formatMessage("error.unknown_type_dna_or_pep", new String[]
380 scoreMatrix = ScoreModels.getInstance()
381 .getDefaultModel(PEP.equals(type));
387 public void traceAlignment()
389 // Find the maximum score along the rhs or bottom row
390 float max = -Float.MAX_VALUE;
392 for (int i = 0; i < seq1.length; i++)
394 if (score[i][seq2.length - 1] > max)
396 max = score[i][seq2.length - 1];
398 maxj = seq2.length - 1;
402 for (int j = 0; j < seq2.length; j++)
404 if (score[seq1.length - 1][j] > max)
406 max = score[seq1.length - 1][j];
407 maxi = seq1.length - 1;
415 maxscore = score[i][j] / 10f;
420 aseq1 = new int[seq1.length + seq2.length];
421 aseq2 = new int[seq1.length + seq2.length];
423 StringBuilder sb1 = new StringBuilder(aseq1.length);
424 StringBuilder sb2 = new StringBuilder(aseq2.length);
426 count = (seq1.length + seq2.length) - 1;
428 while (i > 0 && j > 0)
430 aseq1[count] = seq1[i];
431 sb1.append(s1str.charAt(i));
432 aseq2[count] = seq2[j];
433 sb2.append(s2str.charAt(j));
434 trace = findTrace(i, j);
445 aseq1[count] = GAP_INDEX;
446 sb1.replace(sb1.length() - 1, sb1.length(), "-");
448 else if (trace == -1)
451 aseq2[count] = GAP_INDEX;
452 sb2.replace(sb2.length() - 1, sb2.length(), "-");
461 if (aseq1[count] != GAP_INDEX)
463 aseq1[count] = seq1[i];
464 sb1.append(s1str.charAt(i));
467 if (aseq2[count] != GAP_INDEX)
469 aseq2[count] = seq2[j];
470 sb2.append(s2str.charAt(j));
471 if (aseq1[count]!=GAP_INDEX) {
476 * we built the character strings backwards, so now
477 * reverse them to convert to sequence strings
479 astr1 = sb1.reverse().toString();
480 astr2 = sb2.reverse().toString();
486 public void printAlignment(PrintStream os)
488 // TODO: Use original sequence characters rather than re-translated
489 // characters in output
490 // Find the biggest id length for formatting purposes
491 String s1id = getAlignedSeq1().getDisplayId(true);
492 String s2id = getAlignedSeq2().getDisplayId(true);
493 int nameLength = Math.max(s1id.length(), s2id.length());
494 if (nameLength > MAX_NAME_LENGTH)
496 int truncateBy = nameLength - MAX_NAME_LENGTH;
497 nameLength = MAX_NAME_LENGTH;
498 // JAL-527 - truncate the sequence ids
499 if (s1id.length() > nameLength)
501 int slashPos = s1id.lastIndexOf('/');
502 s1id = s1id.substring(0, slashPos - truncateBy)
503 + s1id.substring(slashPos);
505 if (s2id.length() > nameLength)
507 int slashPos = s2id.lastIndexOf('/');
508 s2id = s2id.substring(0, slashPos - truncateBy)
509 + s2id.substring(slashPos);
512 int len = 72 - nameLength - 1;
513 int nochunks = ((aseq1.length - count) / len)
514 + ((aseq1.length - count) % len > 0 ? 1 : 0);
517 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
518 output.append("Length of alignment = ")
519 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
520 output.append("Sequence ");
521 Format nameFormat = new Format("%" + nameLength + "s");
522 output.append(nameFormat.form(s1id));
523 output.append(" (Sequence length = ")
524 .append(String.valueOf(s1str.length())).append(")")
526 output.append("Sequence ");
527 output.append(nameFormat.form(s2id));
528 output.append(" (Sequence length = ")
529 .append(String.valueOf(s2str.length())).append(")")
530 .append(NEWLINE).append(NEWLINE);
532 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
534 for (int j = 0; j < nochunks; j++)
536 // Print the first aligned sequence
537 output.append(nameFormat.form(s1id)).append(" ");
539 for (int i = 0; i < len; i++)
541 if ((i + (j * len)) < astr1.length())
543 output.append(astr1.charAt(i + (j * len)));
547 output.append(NEWLINE);
548 output.append(nameFormat.form(" ")).append(" ");
551 * Print out the match symbols:
552 * | for exact match (ignoring case)
553 * . if PAM250 score is positive
556 for (int i = 0; i < len; i++)
558 if ((i + (j * len)) < astr1.length())
560 char c1 = astr1.charAt(i + (j * len));
561 char c2 = astr2.charAt(i + (j * len));
562 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
563 if (sameChar && !Comparison.isGap(c1))
568 else if (PEP.equals(type))
570 if (pam250.getPairwiseScore(c1, c2) > 0)
586 // Now print the second aligned sequence
587 output = output.append(NEWLINE);
588 output = output.append(nameFormat.form(s2id)).append(" ");
590 for (int i = 0; i < len; i++)
592 if ((i + (j * len)) < astr2.length())
594 output.append(astr2.charAt(i + (j * len)));
598 output.append(NEWLINE).append(NEWLINE);
601 pid = pid / (aseq1.length - count) * 100;
602 output.append(new Format("Percentage ID = %3.2f\n").form(pid));
603 output.append(NEWLINE);
606 os.print(output.toString());
607 } catch (Exception ex)
620 * @return DOCUMENT ME!
622 public int findTrace(int i, int j)
625 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
627 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
634 else if (F[i][j] == max)
648 else if (E[i][j] == max)
665 public void calcScoreMatrix()
670 // top left hand element
671 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
672 s2str.charAt(0)) * 10;
673 E[0][0] = -GAP_EXTEND_COST;
676 // Calculate the top row first
677 for (int j = 1; j < m; j++)
679 // What should these values be? 0 maybe
680 E[0][j] = max(score[0][j - 1] - GAP_OPEN_COST,
681 E[0][j - 1] - GAP_EXTEND_COST);
682 F[0][j] = -GAP_EXTEND_COST;
684 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
686 score[0][j] = max(pairwiseScore * 10, -GAP_OPEN_COST,
692 // Now do the left hand column
693 for (int i = 1; i < n; i++)
695 E[i][0] = -GAP_OPEN_COST;
696 F[i][0] = max(score[i - 1][0] - GAP_OPEN_COST,
697 F[i - 1][0] - GAP_EXTEND_COST);
699 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
701 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
702 traceback[i][0] = -1;
705 // Now do all the other rows
706 for (int i = 1; i < n; i++)
708 for (int j = 1; j < m; j++)
710 E[i][j] = max(score[i][j - 1] - GAP_OPEN_COST,
711 E[i][j - 1] - GAP_EXTEND_COST);
712 F[i][j] = max(score[i - 1][j] - GAP_OPEN_COST,
713 F[i - 1][j] - GAP_EXTEND_COST);
715 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
717 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
719 traceback[i][j] = findTrace(i, j);
725 * Returns the given sequence with all of the given gap characters removed.
728 * a string of characters to be treated as gaps
734 public static String extractGaps(String gapChars, String seq)
736 if (gapChars == null || seq == null)
740 StringTokenizer str = new StringTokenizer(seq, gapChars);
741 StringBuilder newString = new StringBuilder(seq.length());
743 while (str.hasMoreTokens())
745 newString.append(str.nextToken());
748 return newString.toString();
761 * @return DOCUMENT ME!
763 private static float max(float f1, float f2, float f3)
788 * @return DOCUMENT ME!
790 private static float max(float f1, float f2)
803 * Converts the character string to an array of integers which are the
804 * corresponding indices to the characters in the score matrix
810 int[] indexEncode(String s)
812 int[] encoded = new int[s.length()];
814 for (int i = 0; i < s.length(); i++)
816 char c = s.charAt(i);
817 encoded[i] = scoreMatrix.getMatrixIndex(c);
837 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
840 // TODO method doesn't seem to be referenced anywhere delete??
844 for (int i = 0; i < n; i++)
846 for (int j = 0; j < m; j++)
848 if (mat[i][j] >= max)
853 if (mat[i][j] <= min)
860 jalview.bin.Console.outPrintln(max + " " + min);
862 for (int i = 0; i < n; i++)
864 for (int j = 0; j < m; j++)
869 // jalview.bin.Console.outPrintln(mat[i][j]);
870 float score = (float) (mat[i][j] - min) / (float) (max - min);
871 g.setColor(new Color(score, 0, 0));
872 g.fillRect(x, y, psize, psize);
874 // jalview.bin.Console.outPrintln(x + " " + y + " " + score);
880 * Compute a globally optimal needleman and wunsch alignment between two
886 * AlignSeq.DNA or AlignSeq.PEP
888 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
891 AlignSeq as = new AlignSeq(s1, s2, type);
893 as.calcScoreMatrix();
900 * @return mapping from positions in S1 to corresponding positions in S2
902 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
904 ArrayList<Integer> as1 = new ArrayList<Integer>(),
905 as2 = new ArrayList<Integer>();
906 int pdbpos = s2.getStart() + getSeq2Start() - 2;
907 int alignpos = s1.getStart() + getSeq1Start() - 2;
908 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
909 boolean lastmatch = false;
910 // and now trace the alignment onto the atom set.
911 for (int i = 0; i < astr1.length(); i++)
913 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
924 // ignore case differences
925 if (allowmismatch || (c1 == c2) || (Math.abs(c2 - c1) == ('a' - 'A')))
927 // extend mapping interval
928 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
930 as1.add(Integer.valueOf(alignpos));
931 as2.add(Integer.valueOf(pdbpos));
939 // extend mapping interval
942 as1.add(Integer.valueOf(lp1));
943 as2.add(Integer.valueOf(lp2));
948 // construct range pairs
950 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
951 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
953 for (Integer ip : as1)
959 for (Integer ip : as2)
966 mapseq1[mapseq1.length - 1] = alignpos;
967 mapseq2[mapseq2.length - 1] = pdbpos;
969 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
971 jalview.datamodel.Mapping mapping = new Mapping(map);
977 * matches ochains against al and populates seqs with the best match between
978 * each ochain and the set in al
982 * @param dnaOrProtein
983 * @param removeOldAnnots
984 * when true, old annotation is cleared before new annotation
986 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
987 * List<AlignSeq> alignment between each>
989 public static List<List<? extends Object>> replaceMatchingSeqsWith(
990 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
991 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
992 boolean removeOldAnnots)
994 List<SequenceI> orig = new ArrayList<SequenceI>(),
995 repl = new ArrayList<SequenceI>();
996 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
997 if (al != null && al.getHeight() > 0)
999 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1000 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1002 for (SequenceI sq : ochains)
1004 SequenceI bestm = null;
1005 AlignSeq bestaseq = null;
1006 float bestscore = 0;
1007 for (SequenceI msq : al.getSequences())
1009 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
1010 if (bestm == null || aseq.getMaxScore() > bestscore)
1012 bestscore = aseq.getMaxScore();
1017 // jalview.bin.Console.outPrintln("Best Score for " + (matches.size() +
1021 aligns.add(bestaseq);
1022 al.deleteSequence(bestm);
1024 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1026 SequenceI sq, sp = seqs.get(p);
1028 if ((q = ochains.indexOf(sp)) > -1)
1030 seqs.set(p, sq = matches.get(q));
1033 sq.setName(sp.getName());
1034 sq.setDescription(sp.getDescription());
1036 sq.transferAnnotation(sp,
1037 sp2sq = aligns.get(q).getMappingFromS1(false));
1038 aligs.add(aligns.get(q));
1040 for (int ap = 0; ap < annotations.size();)
1042 if (annotations.get(ap).sequenceRef == sp)
1048 if (removeOldAnnots)
1050 annotations.remove(ap);
1054 AlignmentAnnotation alan = annotations.remove(ap);
1055 alan.liftOver(sq, sp2sq);
1056 alan.setSequenceRef(sq);
1057 sq.addAlignmentAnnotation(alan);
1065 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1067 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1068 Arrays.asList(sq.getAnnotation()));
1073 return Arrays.asList(orig, repl, aligs);
1077 * compute the PID vector used by the redundancy filter.
1079 * @param originalSequences
1080 * - sequences in alignment that are to filtered
1082 * - null or strings to be analysed (typically, visible portion of
1083 * each sequence in alignment)
1085 * - first column in window for calculation
1087 * - last column in window for calculation
1089 * - if true then use ungapped sequence to compute PID
1090 * @return vector containing maximum PID for i-th sequence and any sequences
1091 * longer than that seuqence
1093 public static float[] computeRedundancyMatrix(
1094 SequenceI[] originalSequences, String[] omitHidden, int start,
1095 int end, boolean ungapped)
1097 int height = originalSequences.length;
1098 float[] redundancy = new float[height];
1099 int[] lngth = new int[height];
1100 for (int i = 0; i < height; i++)
1106 // long start = System.currentTimeMillis();
1108 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1112 for (int i = 0; i < height; i++)
1115 for (int j = 0; j < i; j++)
1122 if (omitHidden == null)
1124 seqi = originalSequences[i].getSequenceAsString(start, end);
1125 seqj = originalSequences[j].getSequenceAsString(start, end);
1129 seqi = omitHidden[i];
1130 seqj = omitHidden[j];
1134 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1135 lngth[i] = ug.length();
1143 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1144 lngth[j] = ug.length();
1150 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1152 // use real sequence length rather than string length
1153 if (lngth[j] < lngth[i])
1155 redundancy[j] = Math.max(pid, redundancy[j]);
1159 redundancy[i] = Math.max(pid, redundancy[i]);