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.api.analysis.SimilarityParamsI;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceI;
35 import jalview.util.Comparison;
36 import jalview.util.Format;
37 import jalview.util.MapList;
38 import jalview.util.MessageManager;
40 import java.awt.Color;
41 import java.awt.Graphics;
42 import java.io.PrintStream;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.List;
46 import java.util.StringTokenizer;
56 private static final int MAX_NAME_LENGTH = 30;
58 private static final int GAP_OPEN_COST = 120;
60 private static final int GAP_EXTEND_COST = 20;
62 private static final int GAP_INDEX = -1;
64 public static final String PEP = "pep";
66 public static final String DNA = "dna";
68 private static final String NEWLINE = System.lineSeparator();
76 int[][] traceback; // todo is this actually used?
99 * matches in alignment
103 public String astr1 = "";
105 public String astr2 = "";
108 public int seq1start;
114 public int seq2start;
120 public float maxscore;
124 StringBuffer output = new StringBuffer();
126 String type; // AlignSeq.PEP or AlignSeq.DNA
128 private ScoreMatrix scoreMatrix;
131 * Creates a new AlignSeq object.
134 * first sequence for alignment
136 * second sequence for alignment
138 * molecule type, either AlignSeq.PEP or AlignSeq.DNA
140 public AlignSeq(SequenceI s1, SequenceI s2, String type)
142 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
147 * Creates a new AlignSeq object.
156 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
157 String string2, String type)
159 seqInit(s1, string1.toUpperCase(Locale.ROOT), s2,
160 string2.toUpperCase(Locale.ROOT), type);
166 * @return DOCUMENT ME!
168 public float getMaxScore()
176 * @return DOCUMENT ME!
178 public int getSeq2Start()
186 * @return DOCUMENT ME!
188 public int getSeq2End()
196 * @return DOCUMENT ME!
198 public int getSeq1Start()
206 * @return DOCUMENT ME!
208 public int getSeq1End()
216 * @return DOCUMENT ME!
218 public String getOutput()
220 return output.toString();
226 * @return DOCUMENT ME!
228 public String getAStr1()
236 * @return DOCUMENT ME!
238 public String getAStr2()
246 * @return DOCUMENT ME!
248 public int[] getASeq1()
256 * @return DOCUMENT ME!
258 public int[] getASeq2()
265 * @return aligned instance of Seq 1
267 public SequenceI getAlignedSeq1()
269 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
270 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
271 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
272 alSeq1.setDatasetSequence(
273 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
279 * @return aligned instance of Seq 2
281 public SequenceI getAlignedSeq2()
283 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
284 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
285 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
286 alSeq2.setDatasetSequence(
287 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
291 * fraction of seq2 matched in the alignment
292 * @return NaN or [0..1]
294 public double getS2Coverage()
298 return ((double)match)/((double)s2.getEnd()-s2.getStart()+1);
303 * fraction of seq1 matched in the alignment
304 * @return NaN or [0..1]
306 public double getS1Coverage()
310 return ((double)match)/((double)s1.getEnd()-s1.getStart()+1);
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 string1 and string2 (after removing any existing
345 private void seqInit(String string1, String string2)
347 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
348 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
350 if (s1str.length() == 0 || s2str.length() == 0)
353 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
354 + (s2str.length() == 0 ? s2.getName() : ""));
358 score = new float[s1str.length()][s2str.length()];
360 E = new float[s1str.length()][s2str.length()];
362 F = new float[s1str.length()][s2str.length()];
363 traceback = new int[s1str.length()][s2str.length()];
365 seq1 = indexEncode(s1str);
367 seq2 = indexEncode(s2str);
370 private void setDefaultParams(String moleculeType)
372 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
374 output.append("Wrong type = dna or pep only");
375 throw new Error(MessageManager
376 .formatMessage("error.unknown_type_dna_or_pep", new String[]
381 scoreMatrix = ScoreModels.getInstance()
382 .getDefaultModel(PEP.equals(type));
388 public void traceAlignment()
390 // Find the maximum score along the rhs or bottom row
391 float max = -Float.MAX_VALUE;
393 for (int i = 0; i < seq1.length; i++)
395 if (score[i][seq2.length - 1] > max)
397 max = score[i][seq2.length - 1];
399 maxj = seq2.length - 1;
403 for (int j = 0; j < seq2.length; j++)
405 if (score[seq1.length - 1][j] > max)
407 max = score[seq1.length - 1][j];
408 maxi = seq1.length - 1;
416 maxscore = score[i][j] / 10f;
421 aseq1 = new int[seq1.length + seq2.length];
422 aseq2 = new int[seq1.length + seq2.length];
424 StringBuilder sb1 = new StringBuilder(aseq1.length);
425 StringBuilder sb2 = new StringBuilder(aseq2.length);
427 count = (seq1.length + seq2.length) - 1;
429 while (i > 0 && j > 0)
431 aseq1[count] = seq1[i];
432 sb1.append(s1str.charAt(i));
433 aseq2[count] = seq2[j];
434 sb2.append(s2str.charAt(j));
435 trace = findTrace(i, j);
446 aseq1[count] = GAP_INDEX;
447 sb1.replace(sb1.length() - 1, sb1.length(), "-");
449 else if (trace == -1)
452 aseq2[count] = GAP_INDEX;
453 sb2.replace(sb2.length() - 1, sb2.length(), "-");
462 if (aseq1[count] != GAP_INDEX)
464 aseq1[count] = seq1[i];
465 sb1.append(s1str.charAt(i));
468 if (aseq2[count] != GAP_INDEX)
470 aseq2[count] = seq2[j];
471 sb2.append(s2str.charAt(j));
472 if (aseq1[count]!=GAP_INDEX) {
477 * we built the character strings backwards, so now
478 * reverse them to convert to sequence strings
480 astr1 = sb1.reverse().toString();
481 astr2 = sb2.reverse().toString();
487 public void printAlignment(PrintStream os)
489 // TODO: Use original sequence characters rather than re-translated
490 // characters in output
491 // Find the biggest id length for formatting purposes
492 String s1id = getAlignedSeq1().getDisplayId(true);
493 String s2id = getAlignedSeq2().getDisplayId(true);
494 int nameLength = Math.max(s1id.length(), s2id.length());
495 if (nameLength > MAX_NAME_LENGTH)
497 int truncateBy = nameLength - MAX_NAME_LENGTH;
498 nameLength = MAX_NAME_LENGTH;
499 // JAL-527 - truncate the sequence ids
500 if (s1id.length() > nameLength)
502 int slashPos = s1id.lastIndexOf('/');
503 s1id = s1id.substring(0, slashPos - truncateBy)
504 + s1id.substring(slashPos);
506 if (s2id.length() > nameLength)
508 int slashPos = s2id.lastIndexOf('/');
509 s2id = s2id.substring(0, slashPos - truncateBy)
510 + s2id.substring(slashPos);
513 int len = 72 - nameLength - 1;
514 int nochunks = ((aseq1.length - count) / len)
515 + ((aseq1.length - count) % len > 0 ? 1 : 0);
518 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
519 output.append("Length of alignment = ")
520 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
521 output.append("Sequence ");
522 Format nameFormat = new Format("%" + nameLength + "s");
523 output.append(nameFormat.form(s1id));
524 output.append(" (Sequence length = ")
525 .append(String.valueOf(s1str.length())).append(")")
527 output.append("Sequence ");
528 output.append(nameFormat.form(s2id));
529 output.append(" (Sequence length = ")
530 .append(String.valueOf(s2str.length())).append(")")
531 .append(NEWLINE).append(NEWLINE);
533 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
535 for (int j = 0; j < nochunks; j++)
537 // Print the first aligned sequence
538 output.append(nameFormat.form(s1id)).append(" ");
540 for (int i = 0; i < len; i++)
542 if ((i + (j * len)) < astr1.length())
544 output.append(astr1.charAt(i + (j * len)));
548 output.append(NEWLINE);
549 output.append(nameFormat.form(" ")).append(" ");
552 * Print out the match symbols:
553 * | for exact match (ignoring case)
554 * . if PAM250 score is positive
557 for (int i = 0; i < len; i++)
559 if ((i + (j * len)) < astr1.length())
561 char c1 = astr1.charAt(i + (j * len));
562 char c2 = astr2.charAt(i + (j * len));
563 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
564 if (sameChar && !Comparison.isGap(c1))
569 else if (PEP.equals(type))
571 if (pam250.getPairwiseScore(c1, c2) > 0)
587 // Now print the second aligned sequence
588 output = output.append(NEWLINE);
589 output = output.append(nameFormat.form(s2id)).append(" ");
591 for (int i = 0; i < len; i++)
593 if ((i + (j * len)) < astr2.length())
595 output.append(astr2.charAt(i + (j * len)));
599 output.append(NEWLINE).append(NEWLINE);
602 pid = pid / (aseq1.length - count) * 100;
603 output.append(new Format("Percentage ID = %3.2f\n").form(pid));
604 output.append(NEWLINE);
607 os.print(output.toString());
608 } catch (Exception ex)
621 * @return DOCUMENT ME!
623 public int findTrace(int i, int j)
626 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
628 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
635 else if (F[i][j] == max)
649 else if (E[i][j] == max)
666 public void calcScoreMatrix()
671 // top left hand element
672 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
673 s2str.charAt(0)) * 10;
674 E[0][0] = -GAP_EXTEND_COST;
677 // Calculate the top row first
678 for (int j = 1; j < m; j++)
680 // What should these values be? 0 maybe
681 E[0][j] = max(score[0][j - 1] - GAP_OPEN_COST,
682 E[0][j - 1] - GAP_EXTEND_COST);
683 F[0][j] = -GAP_EXTEND_COST;
685 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
687 score[0][j] = max(pairwiseScore * 10, -GAP_OPEN_COST,
693 // Now do the left hand column
694 for (int i = 1; i < n; i++)
696 E[i][0] = -GAP_OPEN_COST;
697 F[i][0] = max(score[i - 1][0] - GAP_OPEN_COST,
698 F[i - 1][0] - GAP_EXTEND_COST);
700 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
702 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
703 traceback[i][0] = -1;
706 // Now do all the other rows
707 for (int i = 1; i < n; i++)
709 for (int j = 1; j < m; j++)
711 E[i][j] = max(score[i][j - 1] - GAP_OPEN_COST,
712 E[i][j - 1] - GAP_EXTEND_COST);
713 F[i][j] = max(score[i - 1][j] - GAP_OPEN_COST,
714 F[i - 1][j] - GAP_EXTEND_COST);
716 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
718 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
720 traceback[i][j] = findTrace(i, j);
726 * Returns the given sequence with all of the given gap characters removed.
729 * a string of characters to be treated as gaps
735 public static String extractGaps(String gapChars, String seq)
737 if (gapChars == null || seq == null)
741 StringTokenizer str = new StringTokenizer(seq, gapChars);
742 StringBuilder newString = new StringBuilder(seq.length());
744 while (str.hasMoreTokens())
746 newString.append(str.nextToken());
749 return newString.toString();
762 * @return DOCUMENT ME!
764 private static float max(float f1, float f2, float f3)
789 * @return DOCUMENT ME!
791 private static float max(float f1, float f2)
804 * Converts the character string to an array of integers which are the
805 * corresponding indices to the characters in the score matrix
811 int[] indexEncode(String s)
813 int[] encoded = new int[s.length()];
815 for (int i = 0; i < s.length(); i++)
817 char c = s.charAt(i);
818 encoded[i] = scoreMatrix.getMatrixIndex(c);
838 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
841 // TODO method doesn't seem to be referenced anywhere delete??
845 for (int i = 0; i < n; i++)
847 for (int j = 0; j < m; j++)
849 if (mat[i][j] >= max)
854 if (mat[i][j] <= min)
861 jalview.bin.Console.outPrintln(max + " " + min);
863 for (int i = 0; i < n; i++)
865 for (int j = 0; j < m; j++)
870 // jalview.bin.Console.outPrintln(mat[i][j]);
871 float score = (float) (mat[i][j] - min) / (float) (max - min);
872 g.setColor(new Color(score, 0, 0));
873 g.fillRect(x, y, psize, psize);
875 // jalview.bin.Console.outPrintln(x + " " + y + " " + score);
881 * Compute a globally optimal needleman and wunsch alignment between two
887 * AlignSeq.DNA or AlignSeq.PEP
889 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
892 AlignSeq as = new AlignSeq(s1, s2, type);
894 as.calcScoreMatrix();
901 * @return mapping from positions in S1 to corresponding positions in S2
903 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
905 ArrayList<Integer> as1 = new ArrayList<Integer>(),
906 as2 = new ArrayList<Integer>();
907 int pdbpos = s2.getStart() + getSeq2Start() - 2;
908 int alignpos = s1.getStart() + getSeq1Start() - 2;
909 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
910 boolean lastmatch = false;
911 // and now trace the alignment onto the atom set.
912 for (int i = 0; i < astr1.length(); i++)
914 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
925 // ignore case differences
926 if (allowmismatch || (c1 == c2) || (Math.abs(c2 - c1) == ('a' - 'A')))
928 // extend mapping interval
929 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
931 as1.add(Integer.valueOf(alignpos));
932 as2.add(Integer.valueOf(pdbpos));
940 // extend mapping interval
943 as1.add(Integer.valueOf(lp1));
944 as2.add(Integer.valueOf(lp2));
949 // construct range pairs
951 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
952 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
954 for (Integer ip : as1)
960 for (Integer ip : as2)
967 mapseq1[mapseq1.length - 1] = alignpos;
968 mapseq2[mapseq2.length - 1] = pdbpos;
970 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
972 jalview.datamodel.Mapping mapping = new Mapping(map);
978 * matches ochains against al and populates seqs with the best match between
979 * each ochain and the set in al
983 * @param dnaOrProtein
984 * @param removeOldAnnots
985 * when true, old annotation is cleared before new annotation
987 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
988 * List<AlignSeq> alignment between each>
990 public static List<List<? extends Object>> replaceMatchingSeqsWith(
991 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
992 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
993 boolean removeOldAnnots)
995 List<SequenceI> orig = new ArrayList<SequenceI>(),
996 repl = new ArrayList<SequenceI>();
997 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
998 if (al != null && al.getHeight() > 0)
1000 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
1001 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
1003 for (SequenceI sq : ochains)
1005 SequenceI bestm = null;
1006 AlignSeq bestaseq = null;
1007 float bestscore = 0;
1008 for (SequenceI msq : al.getSequences())
1010 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
1011 if (bestm == null || aseq.getMaxScore() > bestscore)
1013 bestscore = aseq.getMaxScore();
1018 // jalview.bin.Console.outPrintln("Best Score for " + (matches.size() +
1022 aligns.add(bestaseq);
1023 al.deleteSequence(bestm);
1025 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
1027 SequenceI sq, sp = seqs.get(p);
1029 if ((q = ochains.indexOf(sp)) > -1)
1031 seqs.set(p, sq = matches.get(q));
1034 sq.setName(sp.getName());
1035 sq.setDescription(sp.getDescription());
1037 sq.transferAnnotation(sp,
1038 sp2sq = aligns.get(q).getMappingFromS1(false));
1039 aligs.add(aligns.get(q));
1041 for (int ap = 0; ap < annotations.size();)
1043 if (annotations.get(ap).sequenceRef == sp)
1049 if (removeOldAnnots)
1051 annotations.remove(ap);
1055 AlignmentAnnotation alan = annotations.remove(ap);
1056 alan.liftOver(sq, sp2sq);
1057 alan.setSequenceRef(sq);
1058 sq.addAlignmentAnnotation(alan);
1066 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1068 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1069 Arrays.asList(sq.getAnnotation()));
1074 return Arrays.asList(orig, repl, aligs);
1078 * compute the PID vector used by the redundancy filter.
1080 * @param originalSequences
1081 * - sequences in alignment that are to filtered
1083 * - null or strings to be analysed (typically, visible portion of
1084 * each sequence in alignment)
1086 * - first column in window for calculation
1088 * - last column in window for calculation
1090 * - if true then use ungapped sequence to compute PID
1091 * @return vector containing maximum PID for i-th sequence and any sequences
1092 * longer than that seuqence
1094 public static float[] computeRedundancyMatrix(
1095 SequenceI[] originalSequences, String[] omitHidden, int start,
1096 int end, boolean ungapped)
1098 int height = originalSequences.length;
1099 float[] redundancy = new float[height];
1100 int[] lngth = new int[height];
1101 for (int i = 0; i < height; i++)
1107 // long start = System.currentTimeMillis();
1109 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1113 for (int i = 0; i < height; i++)
1116 for (int j = 0; j < i; j++)
1123 if (omitHidden == null)
1125 seqi = originalSequences[i].getSequenceAsString(start, end);
1126 seqj = originalSequences[j].getSequenceAsString(start, end);
1130 seqi = omitHidden[i];
1131 seqj = omitHidden[j];
1135 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1136 lngth[i] = ug.length();
1144 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1145 lngth[j] = ug.length();
1151 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1153 // use real sequence length rather than string length
1154 if (lngth[j] < lngth[i])
1156 redundancy[j] = Math.max(pid, redundancy[j]);
1160 redundancy[i] = Math.max(pid, redundancy[i]);
1168 public void setScoreMatrix(ScoreMatrix params)
1172 scoreMatrix = params;