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?
97 public String astr1 = "";
99 public String astr2 = "";
102 public int seq1start;
108 public int seq2start;
114 public float maxscore;
118 StringBuffer output = new StringBuffer();
120 String type; // AlignSeq.PEP or AlignSeq.DNA
122 private ScoreMatrix scoreMatrix;
125 * Creates a new AlignSeq object.
128 * first sequence for alignment
130 * second sequence for alignment
132 * molecule type, either AlignSeq.PEP or AlignSeq.DNA
134 public AlignSeq(SequenceI s1, SequenceI s2, String type)
136 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
141 * Creates a new AlignSeq object.
150 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
151 String string2, String type)
153 seqInit(s1, string1.toUpperCase(Locale.ROOT), s2,
154 string2.toUpperCase(Locale.ROOT), type);
160 * @return DOCUMENT ME!
162 public float getMaxScore()
170 * @return DOCUMENT ME!
172 public int getSeq2Start()
180 * @return DOCUMENT ME!
182 public int getSeq2End()
190 * @return DOCUMENT ME!
192 public int getSeq1Start()
200 * @return DOCUMENT ME!
202 public int getSeq1End()
210 * @return DOCUMENT ME!
212 public String getOutput()
214 return output.toString();
220 * @return DOCUMENT ME!
222 public String getAStr1()
230 * @return DOCUMENT ME!
232 public String getAStr2()
240 * @return DOCUMENT ME!
242 public int[] getASeq1()
250 * @return DOCUMENT ME!
252 public int[] getASeq2()
259 * @return aligned instance of Seq 1
261 public SequenceI getAlignedSeq1()
263 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
264 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
265 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
266 alSeq1.setDatasetSequence(
267 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
273 * @return aligned instance of Seq 2
275 public SequenceI getAlignedSeq2()
277 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
278 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
279 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
280 alSeq2.setDatasetSequence(
281 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
286 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
291 * - string to use for s1
295 * - string to use for s2
299 public void seqInit(SequenceI s1, String string1, SequenceI s2,
300 String string2, String type)
304 setDefaultParams(type);
305 seqInit(string1, string2);
309 * construct score matrix for string1 and string2 (after removing any existing
315 private void seqInit(String string1, String string2)
317 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
318 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
320 if (s1str.length() == 0 || s2str.length() == 0)
323 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
324 + (s2str.length() == 0 ? s2.getName() : ""));
328 score = new float[s1str.length()][s2str.length()];
330 E = new float[s1str.length()][s2str.length()];
332 F = new float[s1str.length()][s2str.length()];
333 traceback = new int[s1str.length()][s2str.length()];
335 seq1 = indexEncode(s1str);
337 seq2 = indexEncode(s2str);
340 private void setDefaultParams(String moleculeType)
342 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
344 output.append("Wrong type = dna or pep only");
345 throw new Error(MessageManager
346 .formatMessage("error.unknown_type_dna_or_pep", new String[]
351 scoreMatrix = ScoreModels.getInstance()
352 .getDefaultModel(PEP.equals(type));
358 public void traceAlignment()
360 // Find the maximum score along the rhs or bottom row
361 float max = -Float.MAX_VALUE;
363 for (int i = 0; i < seq1.length; i++)
365 if (score[i][seq2.length - 1] > max)
367 max = score[i][seq2.length - 1];
369 maxj = seq2.length - 1;
373 for (int j = 0; j < seq2.length; j++)
375 if (score[seq1.length - 1][j] > max)
377 max = score[seq1.length - 1][j];
378 maxi = seq1.length - 1;
386 maxscore = score[i][j] / 10f;
391 aseq1 = new int[seq1.length + seq2.length];
392 aseq2 = new int[seq1.length + seq2.length];
394 StringBuilder sb1 = new StringBuilder(aseq1.length);
395 StringBuilder sb2 = new StringBuilder(aseq2.length);
397 count = (seq1.length + seq2.length) - 1;
399 while (i > 0 && j > 0)
401 aseq1[count] = seq1[i];
402 sb1.append(s1str.charAt(i));
403 aseq2[count] = seq2[j];
404 sb2.append(s2str.charAt(j));
406 trace = findTrace(i, j);
416 aseq1[count] = GAP_INDEX;
417 sb1.replace(sb1.length() - 1, sb1.length(), "-");
419 else if (trace == -1)
422 aseq2[count] = GAP_INDEX;
423 sb2.replace(sb2.length() - 1, sb2.length(), "-");
432 if (aseq1[count] != GAP_INDEX)
434 aseq1[count] = seq1[i];
435 sb1.append(s1str.charAt(i));
438 if (aseq2[count] != GAP_INDEX)
440 aseq2[count] = seq2[j];
441 sb2.append(s2str.charAt(j));
445 * we built the character strings backwards, so now
446 * reverse them to convert to sequence strings
448 astr1 = sb1.reverse().toString();
449 astr2 = sb2.reverse().toString();
455 public void printAlignment(PrintStream os)
457 // TODO: Use original sequence characters rather than re-translated
458 // characters in output
459 // Find the biggest id length for formatting purposes
460 String s1id = getAlignedSeq1().getDisplayId(true);
461 String s2id = getAlignedSeq2().getDisplayId(true);
462 int nameLength = Math.max(s1id.length(), s2id.length());
463 if (nameLength > MAX_NAME_LENGTH)
465 int truncateBy = nameLength - MAX_NAME_LENGTH;
466 nameLength = MAX_NAME_LENGTH;
467 // JAL-527 - truncate the sequence ids
468 if (s1id.length() > nameLength)
470 int slashPos = s1id.lastIndexOf('/');
471 s1id = s1id.substring(0, slashPos - truncateBy)
472 + s1id.substring(slashPos);
474 if (s2id.length() > nameLength)
476 int slashPos = s2id.lastIndexOf('/');
477 s2id = s2id.substring(0, slashPos - truncateBy)
478 + s2id.substring(slashPos);
481 int len = 72 - nameLength - 1;
482 int nochunks = ((aseq1.length - count) / len)
483 + ((aseq1.length - count) % len > 0 ? 1 : 0);
486 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
487 output.append("Length of alignment = ")
488 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
489 output.append("Sequence ");
490 Format nameFormat = new Format("%" + nameLength + "s");
491 output.append(nameFormat.form(s1id));
492 output.append(" (Sequence length = ")
493 .append(String.valueOf(s1str.length())).append(")")
495 output.append("Sequence ");
496 output.append(nameFormat.form(s2id));
497 output.append(" (Sequence length = ")
498 .append(String.valueOf(s2str.length())).append(")")
499 .append(NEWLINE).append(NEWLINE);
501 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
503 for (int j = 0; j < nochunks; j++)
505 // Print the first aligned sequence
506 output.append(nameFormat.form(s1id)).append(" ");
508 for (int i = 0; i < len; i++)
510 if ((i + (j * len)) < astr1.length())
512 output.append(astr1.charAt(i + (j * len)));
516 output.append(NEWLINE);
517 output.append(nameFormat.form(" ")).append(" ");
520 * Print out the match symbols:
521 * | for exact match (ignoring case)
522 * . if PAM250 score is positive
525 for (int i = 0; i < len; i++)
527 if ((i + (j * len)) < astr1.length())
529 char c1 = astr1.charAt(i + (j * len));
530 char c2 = astr2.charAt(i + (j * len));
531 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
532 if (sameChar && !Comparison.isGap(c1))
537 else if (PEP.equals(type))
539 if (pam250.getPairwiseScore(c1, c2) > 0)
555 // Now print the second aligned sequence
556 output = output.append(NEWLINE);
557 output = output.append(nameFormat.form(s2id)).append(" ");
559 for (int i = 0; i < len; i++)
561 if ((i + (j * len)) < astr2.length())
563 output.append(astr2.charAt(i + (j * len)));
567 output.append(NEWLINE).append(NEWLINE);
570 pid = pid / (aseq1.length - count) * 100;
571 output.append(new Format("Percentage ID = %3.2f\n").form(pid));
572 output.append(NEWLINE);
575 os.print(output.toString());
576 } catch (Exception ex)
589 * @return DOCUMENT ME!
591 public int findTrace(int i, int j)
594 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
596 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
603 else if (F[i][j] == max)
617 else if (E[i][j] == max)
634 public void calcScoreMatrix()
639 // top left hand element
640 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
641 s2str.charAt(0)) * 10;
642 E[0][0] = -GAP_EXTEND_COST;
645 // Calculate the top row first
646 for (int j = 1; j < m; j++)
648 // What should these values be? 0 maybe
649 E[0][j] = max(score[0][j - 1] - GAP_OPEN_COST,
650 E[0][j - 1] - GAP_EXTEND_COST);
651 F[0][j] = -GAP_EXTEND_COST;
653 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
655 score[0][j] = max(pairwiseScore * 10, -GAP_OPEN_COST,
661 // Now do the left hand column
662 for (int i = 1; i < n; i++)
664 E[i][0] = -GAP_OPEN_COST;
665 F[i][0] = max(score[i - 1][0] - GAP_OPEN_COST,
666 F[i - 1][0] - GAP_EXTEND_COST);
668 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
670 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
671 traceback[i][0] = -1;
674 // Now do all the other rows
675 for (int i = 1; i < n; i++)
677 for (int j = 1; j < m; j++)
679 E[i][j] = max(score[i][j - 1] - GAP_OPEN_COST,
680 E[i][j - 1] - GAP_EXTEND_COST);
681 F[i][j] = max(score[i - 1][j] - GAP_OPEN_COST,
682 F[i - 1][j] - GAP_EXTEND_COST);
684 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
686 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
688 traceback[i][j] = findTrace(i, j);
694 * Returns the given sequence with all of the given gap characters removed.
697 * a string of characters to be treated as gaps
703 public static String extractGaps(String gapChars, String seq)
705 if (gapChars == null || seq == null)
709 StringTokenizer str = new StringTokenizer(seq, gapChars);
710 StringBuilder newString = new StringBuilder(seq.length());
712 while (str.hasMoreTokens())
714 newString.append(str.nextToken());
717 return newString.toString();
730 * @return DOCUMENT ME!
732 private static float max(float f1, float f2, float f3)
757 * @return DOCUMENT ME!
759 private static float max(float f1, float f2)
772 * Converts the character string to an array of integers which are the
773 * corresponding indices to the characters in the score matrix
779 int[] indexEncode(String s)
781 int[] encoded = new int[s.length()];
783 for (int i = 0; i < s.length(); i++)
785 char c = s.charAt(i);
786 encoded[i] = scoreMatrix.getMatrixIndex(c);
806 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
809 // TODO method doesn't seem to be referenced anywhere delete??
813 for (int i = 0; i < n; i++)
815 for (int j = 0; j < m; j++)
817 if (mat[i][j] >= max)
822 if (mat[i][j] <= min)
829 jalview.bin.Console.outPrintln(max + " " + min);
831 for (int i = 0; i < n; i++)
833 for (int j = 0; j < m; j++)
838 // jalview.bin.Console.outPrintln(mat[i][j]);
839 float score = (float) (mat[i][j] - min) / (float) (max - min);
840 g.setColor(new Color(score, 0, 0));
841 g.fillRect(x, y, psize, psize);
843 // jalview.bin.Console.outPrintln(x + " " + y + " " + score);
849 * Compute a globally optimal needleman and wunsch alignment between two
855 * AlignSeq.DNA or AlignSeq.PEP
857 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
860 AlignSeq as = new AlignSeq(s1, s2, type);
862 as.calcScoreMatrix();
869 * @return mapping from positions in S1 to corresponding positions in S2
871 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
873 ArrayList<Integer> as1 = new ArrayList<Integer>(),
874 as2 = new ArrayList<Integer>();
875 int pdbpos = s2.getStart() + getSeq2Start() - 2;
876 int alignpos = s1.getStart() + getSeq1Start() - 2;
877 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
878 boolean lastmatch = false;
879 // and now trace the alignment onto the atom set.
880 for (int i = 0; i < astr1.length(); i++)
882 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
893 // ignore case differences
894 if (allowmismatch || (c1 == c2) || (Math.abs(c2 - c1) == ('a' - 'A')))
896 // extend mapping interval
897 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
899 as1.add(Integer.valueOf(alignpos));
900 as2.add(Integer.valueOf(pdbpos));
908 // extend mapping interval
911 as1.add(Integer.valueOf(lp1));
912 as2.add(Integer.valueOf(lp2));
917 // construct range pairs
919 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
920 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
922 for (Integer ip : as1)
928 for (Integer ip : as2)
935 mapseq1[mapseq1.length - 1] = alignpos;
936 mapseq2[mapseq2.length - 1] = pdbpos;
938 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
940 jalview.datamodel.Mapping mapping = new Mapping(map);
946 * matches ochains against al and populates seqs with the best match between
947 * each ochain and the set in al
951 * @param dnaOrProtein
952 * @param removeOldAnnots
953 * when true, old annotation is cleared before new annotation
955 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
956 * List<AlignSeq> alignment between each>
958 public static List<List<? extends Object>> replaceMatchingSeqsWith(
959 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
960 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
961 boolean removeOldAnnots)
963 List<SequenceI> orig = new ArrayList<SequenceI>(),
964 repl = new ArrayList<SequenceI>();
965 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
966 if (al != null && al.getHeight() > 0)
968 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
969 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
971 for (SequenceI sq : ochains)
973 SequenceI bestm = null;
974 AlignSeq bestaseq = null;
976 for (SequenceI msq : al.getSequences())
978 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
979 if (bestm == null || aseq.getMaxScore() > bestscore)
981 bestscore = aseq.getMaxScore();
986 // jalview.bin.Console.outPrintln("Best Score for " + (matches.size() +
990 aligns.add(bestaseq);
991 al.deleteSequence(bestm);
993 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
995 SequenceI sq, sp = seqs.get(p);
997 if ((q = ochains.indexOf(sp)) > -1)
999 seqs.set(p, sq = matches.get(q));
1002 sq.setName(sp.getName());
1003 sq.setDescription(sp.getDescription());
1005 sq.transferAnnotation(sp,
1006 sp2sq = aligns.get(q).getMappingFromS1(false));
1007 aligs.add(aligns.get(q));
1009 for (int ap = 0; ap < annotations.size();)
1011 if (annotations.get(ap).sequenceRef == sp)
1017 if (removeOldAnnots)
1019 annotations.remove(ap);
1023 AlignmentAnnotation alan = annotations.remove(ap);
1024 alan.liftOver(sq, sp2sq);
1025 alan.setSequenceRef(sq);
1026 sq.addAlignmentAnnotation(alan);
1034 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1036 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1037 Arrays.asList(sq.getAnnotation()));
1042 return Arrays.asList(orig, repl, aligs);
1046 * compute the PID vector used by the redundancy filter.
1048 * @param originalSequences
1049 * - sequences in alignment that are to filtered
1051 * - null or strings to be analysed (typically, visible portion of
1052 * each sequence in alignment)
1054 * - first column in window for calculation
1056 * - last column in window for calculation
1058 * - if true then use ungapped sequence to compute PID
1059 * @return vector containing maximum PID for i-th sequence and any sequences
1060 * longer than that seuqence
1062 public static float[] computeRedundancyMatrix(
1063 SequenceI[] originalSequences, String[] omitHidden, int start,
1064 int end, boolean ungapped)
1066 int height = originalSequences.length;
1067 float[] redundancy = new float[height];
1068 int[] lngth = new int[height];
1069 for (int i = 0; i < height; i++)
1075 // long start = System.currentTimeMillis();
1077 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1081 for (int i = 0; i < height; i++)
1084 for (int j = 0; j < i; j++)
1091 if (omitHidden == null)
1093 seqi = originalSequences[i].getSequenceAsString(start, end);
1094 seqj = originalSequences[j].getSequenceAsString(start, end);
1098 seqi = omitHidden[i];
1099 seqj = omitHidden[j];
1103 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1104 lngth[i] = ug.length();
1112 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1113 lngth[j] = ug.length();
1119 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1121 // use real sequence length rather than string length
1122 if (lngth[j] < lngth[i])
1124 redundancy[j] = Math.max(pid, redundancy[j]);
1128 redundancy[i] = Math.max(pid, redundancy[i]);