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, string2.toUpperCase(Locale.ROOT), type);
159 * @return DOCUMENT ME!
161 public float getMaxScore()
169 * @return DOCUMENT ME!
171 public int getSeq2Start()
179 * @return DOCUMENT ME!
181 public int getSeq2End()
189 * @return DOCUMENT ME!
191 public int getSeq1Start()
199 * @return DOCUMENT ME!
201 public int getSeq1End()
209 * @return DOCUMENT ME!
211 public String getOutput()
213 return output.toString();
219 * @return DOCUMENT ME!
221 public String getAStr1()
229 * @return DOCUMENT ME!
231 public String getAStr2()
239 * @return DOCUMENT ME!
241 public int[] getASeq1()
249 * @return DOCUMENT ME!
251 public int[] getASeq2()
258 * @return aligned instance of Seq 1
260 public SequenceI getAlignedSeq1()
262 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
263 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
264 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
265 alSeq1.setDatasetSequence(
266 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
272 * @return aligned instance of Seq 2
274 public SequenceI getAlignedSeq2()
276 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
277 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
278 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
279 alSeq2.setDatasetSequence(
280 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
285 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
290 * - string to use for s1
294 * - string to use for s2
298 public void seqInit(SequenceI s1, String string1, SequenceI s2,
299 String string2, String type)
303 setDefaultParams(type);
304 seqInit(string1, string2);
308 * construct score matrix for string1 and string2 (after removing any existing
314 private void seqInit(String string1, String string2)
316 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
317 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
319 if (s1str.length() == 0 || s2str.length() == 0)
322 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
323 + (s2str.length() == 0 ? s2.getName() : ""));
327 score = new float[s1str.length()][s2str.length()];
329 E = new float[s1str.length()][s2str.length()];
331 F = new float[s1str.length()][s2str.length()];
332 traceback = new int[s1str.length()][s2str.length()];
334 seq1 = indexEncode(s1str);
336 seq2 = indexEncode(s2str);
339 private void setDefaultParams(String moleculeType)
341 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
343 output.append("Wrong type = dna or pep only");
344 throw new Error(MessageManager
345 .formatMessage("error.unknown_type_dna_or_pep", new String[]
350 scoreMatrix = ScoreModels.getInstance()
351 .getDefaultModel(PEP.equals(type));
357 public void traceAlignment()
359 // Find the maximum score along the rhs or bottom row
360 float max = -Float.MAX_VALUE;
362 for (int i = 0; i < seq1.length; i++)
364 if (score[i][seq2.length - 1] > max)
366 max = score[i][seq2.length - 1];
368 maxj = seq2.length - 1;
372 for (int j = 0; j < seq2.length; j++)
374 if (score[seq1.length - 1][j] > max)
376 max = score[seq1.length - 1][j];
377 maxi = seq1.length - 1;
385 maxscore = score[i][j] / 10f;
390 aseq1 = new int[seq1.length + seq2.length];
391 aseq2 = new int[seq1.length + seq2.length];
393 StringBuilder sb1 = new StringBuilder(aseq1.length);
394 StringBuilder sb2 = new StringBuilder(aseq2.length);
396 count = (seq1.length + seq2.length) - 1;
398 while (i > 0 && j > 0)
400 aseq1[count] = seq1[i];
401 sb1.append(s1str.charAt(i));
402 aseq2[count] = seq2[j];
403 sb2.append(s2str.charAt(j));
405 trace = findTrace(i, j);
415 aseq1[count] = GAP_INDEX;
416 sb1.replace(sb1.length() - 1, sb1.length(), "-");
418 else if (trace == -1)
421 aseq2[count] = GAP_INDEX;
422 sb2.replace(sb2.length() - 1, sb2.length(), "-");
431 if (aseq1[count] != GAP_INDEX)
433 aseq1[count] = seq1[i];
434 sb1.append(s1str.charAt(i));
437 if (aseq2[count] != GAP_INDEX)
439 aseq2[count] = seq2[j];
440 sb2.append(s2str.charAt(j));
444 * we built the character strings backwards, so now
445 * reverse them to convert to sequence strings
447 astr1 = sb1.reverse().toString();
448 astr2 = sb2.reverse().toString();
454 public void printAlignment(PrintStream os)
456 // TODO: Use original sequence characters rather than re-translated
457 // characters in output
458 // Find the biggest id length for formatting purposes
459 String s1id = getAlignedSeq1().getDisplayId(true);
460 String s2id = getAlignedSeq2().getDisplayId(true);
461 int nameLength = Math.max(s1id.length(), s2id.length());
462 if (nameLength > MAX_NAME_LENGTH)
464 int truncateBy = nameLength - MAX_NAME_LENGTH;
465 nameLength = MAX_NAME_LENGTH;
466 // JAL-527 - truncate the sequence ids
467 if (s1id.length() > nameLength)
469 int slashPos = s1id.lastIndexOf('/');
470 s1id = s1id.substring(0, slashPos - truncateBy)
471 + s1id.substring(slashPos);
473 if (s2id.length() > nameLength)
475 int slashPos = s2id.lastIndexOf('/');
476 s2id = s2id.substring(0, slashPos - truncateBy)
477 + s2id.substring(slashPos);
480 int len = 72 - nameLength - 1;
481 int nochunks = ((aseq1.length - count) / len)
482 + ((aseq1.length - count) % len > 0 ? 1 : 0);
485 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
486 output.append("Length of alignment = ")
487 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
488 output.append("Sequence ");
489 Format nameFormat = new Format("%" + nameLength + "s");
490 output.append(nameFormat.form(s1id));
491 output.append(" (Sequence length = ")
492 .append(String.valueOf(s1str.length())).append(")")
494 output.append("Sequence ");
495 output.append(nameFormat.form(s2id));
496 output.append(" (Sequence length = ")
497 .append(String.valueOf(s2str.length())).append(")")
498 .append(NEWLINE).append(NEWLINE);
500 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
502 for (int j = 0; j < nochunks; j++)
504 // Print the first aligned sequence
505 output.append(nameFormat.form(s1id)).append(" ");
507 for (int i = 0; i < len; i++)
509 if ((i + (j * len)) < astr1.length())
511 output.append(astr1.charAt(i + (j * len)));
515 output.append(NEWLINE);
516 output.append(nameFormat.form(" ")).append(" ");
519 * Print out the match symbols:
520 * | for exact match (ignoring case)
521 * . if PAM250 score is positive
524 for (int i = 0; i < len; i++)
526 if ((i + (j * len)) < astr1.length())
528 char c1 = astr1.charAt(i + (j * len));
529 char c2 = astr2.charAt(i + (j * len));
530 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
531 if (sameChar && !Comparison.isGap(c1))
536 else if (PEP.equals(type))
538 if (pam250.getPairwiseScore(c1, c2) > 0)
554 // Now print the second aligned sequence
555 output = output.append(NEWLINE);
556 output = output.append(nameFormat.form(s2id)).append(" ");
558 for (int i = 0; i < len; i++)
560 if ((i + (j * len)) < astr2.length())
562 output.append(astr2.charAt(i + (j * len)));
566 output.append(NEWLINE).append(NEWLINE);
569 pid = pid / (aseq1.length - count) * 100;
570 output.append(new Format("Percentage ID = %3.2f\n").form(pid));
571 output.append(NEWLINE);
574 os.print(output.toString());
575 } catch (Exception ex)
588 * @return DOCUMENT ME!
590 public int findTrace(int i, int j)
593 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
595 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
602 else if (F[i][j] == max)
616 else if (E[i][j] == max)
633 public void calcScoreMatrix()
638 // top left hand element
639 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
640 s2str.charAt(0)) * 10;
641 E[0][0] = -GAP_EXTEND_COST;
644 // Calculate the top row first
645 for (int j = 1; j < m; j++)
647 // What should these values be? 0 maybe
648 E[0][j] = max(score[0][j - 1] - GAP_OPEN_COST, E[0][j - 1] - GAP_EXTEND_COST);
649 F[0][j] = -GAP_EXTEND_COST;
651 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
653 score[0][j] = max(pairwiseScore * 10, -GAP_OPEN_COST, -GAP_EXTEND_COST);
658 // Now do the left hand column
659 for (int i = 1; i < n; i++)
661 E[i][0] = -GAP_OPEN_COST;
662 F[i][0] = max(score[i - 1][0] - GAP_OPEN_COST, F[i - 1][0] - GAP_EXTEND_COST);
664 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
666 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
667 traceback[i][0] = -1;
670 // Now do all the other rows
671 for (int i = 1; i < n; i++)
673 for (int j = 1; j < m; j++)
675 E[i][j] = max(score[i][j - 1] - GAP_OPEN_COST, E[i][j - 1] - GAP_EXTEND_COST);
676 F[i][j] = max(score[i - 1][j] - GAP_OPEN_COST, F[i - 1][j] - GAP_EXTEND_COST);
678 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
680 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
682 traceback[i][j] = findTrace(i, j);
688 * Returns the given sequence with all of the given gap characters removed.
691 * a string of characters to be treated as gaps
697 public static String extractGaps(String gapChars, String seq)
699 if (gapChars == null || seq == null)
703 StringTokenizer str = new StringTokenizer(seq, gapChars);
704 StringBuilder newString = new StringBuilder(seq.length());
706 while (str.hasMoreTokens())
708 newString.append(str.nextToken());
711 return newString.toString();
724 * @return DOCUMENT ME!
726 private static float max(float f1, float f2, float f3)
751 * @return DOCUMENT ME!
753 private static float max(float f1, float f2)
766 * Converts the character string to an array of integers which are the
767 * corresponding indices to the characters in the score matrix
773 int[] indexEncode(String s)
775 int[] encoded = new int[s.length()];
777 for (int i = 0; i < s.length(); i++)
779 char c = s.charAt(i);
780 encoded[i] = scoreMatrix.getMatrixIndex(c);
800 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
803 // TODO method doesn't seem to be referenced anywhere delete??
807 for (int i = 0; i < n; i++)
809 for (int j = 0; j < m; j++)
811 if (mat[i][j] >= max)
816 if (mat[i][j] <= min)
823 System.out.println(max + " " + min);
825 for (int i = 0; i < n; i++)
827 for (int j = 0; j < m; j++)
832 // System.out.println(mat[i][j]);
833 float score = (float) (mat[i][j] - min) / (float) (max - min);
834 g.setColor(new Color(score, 0, 0));
835 g.fillRect(x, y, psize, psize);
837 // System.out.println(x + " " + y + " " + score);
843 * Compute a globally optimal needleman and wunsch alignment between two
849 * AlignSeq.DNA or AlignSeq.PEP
851 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
854 AlignSeq as = new AlignSeq(s1, s2, type);
856 as.calcScoreMatrix();
863 * @return mapping from positions in S1 to corresponding positions in S2
865 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
867 ArrayList<Integer> as1 = new ArrayList<Integer>(),
868 as2 = new ArrayList<Integer>();
869 int pdbpos = s2.getStart() + getSeq2Start() - 2;
870 int alignpos = s1.getStart() + getSeq1Start() - 2;
871 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
872 boolean lastmatch = false;
873 // and now trace the alignment onto the atom set.
874 for (int i = 0; i < astr1.length(); i++)
876 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
887 if (allowmismatch || c1 == c2)
889 // extend mapping interval
890 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
892 as1.add(Integer.valueOf(alignpos));
893 as2.add(Integer.valueOf(pdbpos));
901 // extend mapping interval
904 as1.add(Integer.valueOf(lp1));
905 as2.add(Integer.valueOf(lp2));
910 // construct range pairs
912 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
913 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
915 for (Integer ip : as1)
921 for (Integer ip : as2)
928 mapseq1[mapseq1.length - 1] = alignpos;
929 mapseq2[mapseq2.length - 1] = pdbpos;
931 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
933 jalview.datamodel.Mapping mapping = new Mapping(map);
939 * matches ochains against al and populates seqs with the best match between
940 * each ochain and the set in al
944 * @param dnaOrProtein
945 * @param removeOldAnnots
946 * when true, old annotation is cleared before new annotation
948 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
949 * List<AlignSeq> alignment between each>
951 public static List<List<? extends Object>> replaceMatchingSeqsWith(
952 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
953 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
954 boolean removeOldAnnots)
956 List<SequenceI> orig = new ArrayList<SequenceI>(),
957 repl = new ArrayList<SequenceI>();
958 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
959 if (al != null && al.getHeight() > 0)
961 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
962 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
964 for (SequenceI sq : ochains)
966 SequenceI bestm = null;
967 AlignSeq bestaseq = null;
969 for (SequenceI msq : al.getSequences())
971 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
972 if (bestm == null || aseq.getMaxScore() > bestscore)
974 bestscore = aseq.getMaxScore();
979 // System.out.println("Best Score for " + (matches.size() + 1) + " :"
982 aligns.add(bestaseq);
983 al.deleteSequence(bestm);
985 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
987 SequenceI sq, sp = seqs.get(p);
989 if ((q = ochains.indexOf(sp)) > -1)
991 seqs.set(p, sq = matches.get(q));
994 sq.setName(sp.getName());
995 sq.setDescription(sp.getDescription());
997 sq.transferAnnotation(sp,
998 sp2sq = aligns.get(q).getMappingFromS1(false));
999 aligs.add(aligns.get(q));
1001 for (int ap = 0; ap < annotations.size();)
1003 if (annotations.get(ap).sequenceRef == sp)
1009 if (removeOldAnnots)
1011 annotations.remove(ap);
1015 AlignmentAnnotation alan = annotations.remove(ap);
1016 alan.liftOver(sq, sp2sq);
1017 alan.setSequenceRef(sq);
1018 sq.addAlignmentAnnotation(alan);
1026 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1028 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1029 Arrays.asList(sq.getAnnotation()));
1034 return Arrays.asList(orig, repl, aligs);
1038 * compute the PID vector used by the redundancy filter.
1040 * @param originalSequences
1041 * - sequences in alignment that are to filtered
1043 * - null or strings to be analysed (typically, visible portion of
1044 * each sequence in alignment)
1046 * - first column in window for calculation
1048 * - last column in window for calculation
1050 * - if true then use ungapped sequence to compute PID
1051 * @return vector containing maximum PID for i-th sequence and any sequences
1052 * longer than that seuqence
1054 public static float[] computeRedundancyMatrix(
1055 SequenceI[] originalSequences, String[] omitHidden, int start,
1056 int end, boolean ungapped)
1058 int height = originalSequences.length;
1059 float[] redundancy = new float[height];
1060 int[] lngth = new int[height];
1061 for (int i = 0; i < height; i++)
1067 // long start = System.currentTimeMillis();
1069 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1073 for (int i = 0; i < height; i++)
1076 for (int j = 0; j < i; j++)
1083 if (omitHidden == null)
1085 seqi = originalSequences[i].getSequenceAsString(start, end);
1086 seqj = originalSequences[j].getSequenceAsString(start, end);
1090 seqi = omitHidden[i];
1091 seqj = omitHidden[j];
1095 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1096 lngth[i] = ug.length();
1104 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1105 lngth[j] = ug.length();
1111 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1113 // use real sequence length rather than string length
1114 if (lngth[j] < lngth[i])
1116 redundancy[j] = Math.max(pid, redundancy[j]);
1120 redundancy[i] = Math.max(pid, redundancy[i]);