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.PIDModel;
24 import jalview.analysis.scoremodels.ScoreMatrix;
25 import jalview.analysis.scoremodels.ScoreModels;
26 import jalview.analysis.scoremodels.SimilarityParams;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Mapping;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceI;
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.io.PrintStream;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.List;
43 import java.util.StringTokenizer;
53 private static final int MAX_NAME_LENGTH = 30;
55 private static final int GAP_OPEN_COST = 120;
57 private static final int GAP_EXTEND_COST = 20;
59 private static final int GAP_INDEX = -1;
61 public static final String PEP = "pep";
63 public static final String DNA = "dna";
65 private static final String NEWLINE = System.lineSeparator();
73 int[][] traceback; // todo is this actually used?
95 public String astr1 = "";
97 public String astr2 = "";
100 public int seq1start;
106 public int seq2start;
112 public float maxscore;
116 StringBuffer output = new StringBuffer();
118 String type; // AlignSeq.PEP or AlignSeq.DNA
120 private ScoreMatrix scoreMatrix;
123 * Creates a new AlignSeq object.
126 * first sequence for alignment
128 * second sequence for alignment
130 * molecule type, either AlignSeq.PEP or AlignSeq.DNA
132 public AlignSeq(SequenceI s1, SequenceI s2, String type)
134 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
139 * Creates a new AlignSeq object.
148 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
149 String string2, String type)
151 seqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
157 * @return DOCUMENT ME!
159 public float getMaxScore()
167 * @return DOCUMENT ME!
169 public int getSeq2Start()
177 * @return DOCUMENT ME!
179 public int getSeq2End()
187 * @return DOCUMENT ME!
189 public int getSeq1Start()
197 * @return DOCUMENT ME!
199 public int getSeq1End()
207 * @return DOCUMENT ME!
209 public String getOutput()
211 return output.toString();
217 * @return DOCUMENT ME!
219 public String getAStr1()
227 * @return DOCUMENT ME!
229 public String getAStr2()
237 * @return DOCUMENT ME!
239 public int[] getASeq1()
247 * @return DOCUMENT ME!
249 public int[] getASeq2()
256 * @return aligned instance of Seq 1
258 public SequenceI getAlignedSeq1()
260 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
261 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
262 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
263 alSeq1.setDatasetSequence(
264 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
270 * @return aligned instance of Seq 2
272 public SequenceI getAlignedSeq2()
274 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
275 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
276 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
277 alSeq2.setDatasetSequence(
278 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
283 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
288 * - string to use for s1
292 * - string to use for s2
296 public void seqInit(SequenceI s1, String string1, SequenceI s2,
297 String string2, String type)
301 setDefaultParams(type);
302 seqInit(string1, string2);
306 * construct score matrix for string1 and string2 (after removing any existing
312 private void seqInit(String string1, String string2)
314 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
315 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
317 if (s1str.length() == 0 || s2str.length() == 0)
320 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
321 + (s2str.length() == 0 ? s2.getName() : ""));
325 score = new float[s1str.length()][s2str.length()];
327 E = new float[s1str.length()][s2str.length()];
329 F = new float[s1str.length()][s2str.length()];
330 traceback = new int[s1str.length()][s2str.length()];
332 seq1 = indexEncode(s1str);
334 seq2 = indexEncode(s2str);
337 private void setDefaultParams(String moleculeType)
339 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
341 output.append("Wrong type = dna or pep only");
342 throw new Error(MessageManager
343 .formatMessage("error.unknown_type_dna_or_pep", new String[]
348 scoreMatrix = ScoreModels.getInstance()
349 .getDefaultModel(PEP.equals(type));
355 public void traceAlignment()
357 // Find the maximum score along the rhs or bottom row
358 float max = -Float.MAX_VALUE;
360 for (int i = 0; i < seq1.length; i++)
362 if (score[i][seq2.length - 1] > max)
364 max = score[i][seq2.length - 1];
366 maxj = seq2.length - 1;
370 for (int j = 0; j < seq2.length; j++)
372 if (score[seq1.length - 1][j] > max)
374 max = score[seq1.length - 1][j];
375 maxi = seq1.length - 1;
383 maxscore = score[i][j] / 10f;
388 aseq1 = new int[seq1.length + seq2.length];
389 aseq2 = new int[seq1.length + seq2.length];
391 StringBuilder sb1 = new StringBuilder(aseq1.length);
392 StringBuilder sb2 = new StringBuilder(aseq2.length);
394 count = (seq1.length + seq2.length) - 1;
396 while (i > 0 && j > 0)
398 aseq1[count] = seq1[i];
399 sb1.append(s1str.charAt(i));
400 aseq2[count] = seq2[j];
401 sb2.append(s2str.charAt(j));
403 trace = findTrace(i, j);
413 aseq1[count] = GAP_INDEX;
414 sb1.replace(sb1.length() - 1, sb1.length(), "-");
416 else if (trace == -1)
419 aseq2[count] = GAP_INDEX;
420 sb2.replace(sb2.length() - 1, sb2.length(), "-");
429 if (aseq1[count] != GAP_INDEX)
431 aseq1[count] = seq1[i];
432 sb1.append(s1str.charAt(i));
435 if (aseq2[count] != GAP_INDEX)
437 aseq2[count] = seq2[j];
438 sb2.append(s2str.charAt(j));
442 * we built the character strings backwards, so now
443 * reverse them to convert to sequence strings
445 astr1 = sb1.reverse().toString();
446 astr2 = sb2.reverse().toString();
452 public void printAlignment(PrintStream os)
454 // TODO: Use original sequence characters rather than re-translated
455 // characters in output
456 // Find the biggest id length for formatting purposes
457 String s1id = getAlignedSeq1().getDisplayId(true);
458 String s2id = getAlignedSeq2().getDisplayId(true);
459 int nameLength = Math.max(s1id.length(), s2id.length());
460 if (nameLength > MAX_NAME_LENGTH)
462 int truncateBy = nameLength - MAX_NAME_LENGTH;
463 nameLength = MAX_NAME_LENGTH;
464 // JAL-527 - truncate the sequence ids
465 if (s1id.length() > nameLength)
467 int slashPos = s1id.lastIndexOf('/');
468 s1id = s1id.substring(0, slashPos - truncateBy)
469 + s1id.substring(slashPos);
471 if (s2id.length() > nameLength)
473 int slashPos = s2id.lastIndexOf('/');
474 s2id = s2id.substring(0, slashPos - truncateBy)
475 + s2id.substring(slashPos);
478 int len = 72 - nameLength - 1;
479 int nochunks = ((aseq1.length - count) / len)
480 + ((aseq1.length - count) % len > 0 ? 1 : 0);
483 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
484 output.append("Length of alignment = ")
485 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
486 output.append("Sequence ");
487 Format nameFormat = new Format("%" + nameLength + "s");
488 output.append(nameFormat.form(s1id));
489 output.append(" (Sequence length = ")
490 .append(String.valueOf(s1str.length())).append(")")
492 output.append("Sequence ");
493 output.append(nameFormat.form(s2id));
494 output.append(" (Sequence length = ")
495 .append(String.valueOf(s2str.length())).append(")")
496 .append(NEWLINE).append(NEWLINE);
498 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
500 for (int j = 0; j < nochunks; j++)
502 // Print the first aligned sequence
503 output.append(nameFormat.form(s1id)).append(" ");
505 for (int i = 0; i < len; i++)
507 if ((i + (j * len)) < astr1.length())
509 output.append(astr1.charAt(i + (j * len)));
513 output.append(NEWLINE);
514 output.append(nameFormat.form(" ")).append(" ");
517 * Print out the match symbols:
518 * | for exact match (ignoring case)
519 * . if PAM250 score is positive
522 for (int i = 0; i < len; i++)
524 if ((i + (j * len)) < astr1.length())
526 char c1 = astr1.charAt(i + (j * len));
527 char c2 = astr2.charAt(i + (j * len));
528 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
529 if (sameChar && !Comparison.isGap(c1))
534 else if (PEP.equals(type))
536 if (pam250.getPairwiseScore(c1, c2) > 0)
552 // Now print the second aligned sequence
553 output = output.append(NEWLINE);
554 output = output.append(nameFormat.form(s2id)).append(" ");
556 for (int i = 0; i < len; i++)
558 if ((i + (j * len)) < astr2.length())
560 output.append(astr2.charAt(i + (j * len)));
564 output.append(NEWLINE).append(NEWLINE);
567 pid = pid / (aseq1.length - count) * 100;
568 output.append(new Format("Percentage ID = %3.2f\n").form(pid));
569 output.append(NEWLINE);
572 os.print(output.toString());
573 } catch (Exception ex)
586 * @return DOCUMENT ME!
588 public int findTrace(int i, int j)
591 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
593 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
600 else if (F[i][j] == max)
614 else if (E[i][j] == max)
631 public void calcScoreMatrix()
636 // top left hand element
637 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
638 s2str.charAt(0)) * 10;
639 E[0][0] = -GAP_EXTEND_COST;
642 // Calculate the top row first
643 for (int j = 1; j < m; j++)
645 // What should these values be? 0 maybe
646 E[0][j] = max(score[0][j - 1] - GAP_OPEN_COST, E[0][j - 1] - GAP_EXTEND_COST);
647 F[0][j] = -GAP_EXTEND_COST;
649 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
651 score[0][j] = max(pairwiseScore * 10, -GAP_OPEN_COST, -GAP_EXTEND_COST);
656 // Now do the left hand column
657 for (int i = 1; i < n; i++)
659 E[i][0] = -GAP_OPEN_COST;
660 F[i][0] = max(score[i - 1][0] - GAP_OPEN_COST, F[i - 1][0] - GAP_EXTEND_COST);
662 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
664 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
665 traceback[i][0] = -1;
668 // Now do all the other rows
669 for (int i = 1; i < n; i++)
671 for (int j = 1; j < m; j++)
673 E[i][j] = max(score[i][j - 1] - GAP_OPEN_COST, E[i][j - 1] - GAP_EXTEND_COST);
674 F[i][j] = max(score[i - 1][j] - GAP_OPEN_COST, F[i - 1][j] - GAP_EXTEND_COST);
676 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
678 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
680 traceback[i][j] = findTrace(i, j);
686 * Returns the given sequence with all of the given gap characters removed.
689 * a string of characters to be treated as gaps
695 public static String extractGaps(String gapChars, String seq)
697 if (gapChars == null || seq == null)
701 StringTokenizer str = new StringTokenizer(seq, gapChars);
702 StringBuilder newString = new StringBuilder(seq.length());
704 while (str.hasMoreTokens())
706 newString.append(str.nextToken());
709 return newString.toString();
722 * @return DOCUMENT ME!
724 private static float max(float f1, float f2, float f3)
749 * @return DOCUMENT ME!
751 private static float max(float f1, float f2)
764 * Converts the character string to an array of integers which are the
765 * corresponding indices to the characters in the score matrix
771 int[] indexEncode(String s)
773 int[] encoded = new int[s.length()];
775 for (int i = 0; i < s.length(); i++)
777 char c = s.charAt(i);
778 encoded[i] = scoreMatrix.getMatrixIndex(c);
798 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
801 // TODO method doesn't seem to be referenced anywhere delete??
805 for (int i = 0; i < n; i++)
807 for (int j = 0; j < m; j++)
809 if (mat[i][j] >= max)
814 if (mat[i][j] <= min)
821 System.out.println(max + " " + min);
823 for (int i = 0; i < n; i++)
825 for (int j = 0; j < m; j++)
830 // System.out.println(mat[i][j]);
831 float score = (float) (mat[i][j] - min) / (float) (max - min);
832 g.setColor(new Color(score, 0, 0));
833 g.fillRect(x, y, psize, psize);
835 // System.out.println(x + " " + y + " " + score);
841 * Compute a globally optimal needleman and wunsch alignment between two
847 * AlignSeq.DNA or AlignSeq.PEP
849 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
852 AlignSeq as = new AlignSeq(s1, s2, type);
854 as.calcScoreMatrix();
861 * @return mapping from positions in S1 to corresponding positions in S2
863 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
865 ArrayList<Integer> as1 = new ArrayList<Integer>(),
866 as2 = new ArrayList<Integer>();
867 int pdbpos = s2.getStart() + getSeq2Start() - 2;
868 int alignpos = s1.getStart() + getSeq1Start() - 2;
869 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
870 boolean lastmatch = false;
871 // and now trace the alignment onto the atom set.
872 for (int i = 0; i < astr1.length(); i++)
874 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
885 if (allowmismatch || c1 == c2)
887 // extend mapping interval
888 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
890 as1.add(Integer.valueOf(alignpos));
891 as2.add(Integer.valueOf(pdbpos));
899 // extend mapping interval
902 as1.add(Integer.valueOf(lp1));
903 as2.add(Integer.valueOf(lp2));
908 // construct range pairs
910 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
911 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
913 for (Integer ip : as1)
919 for (Integer ip : as2)
926 mapseq1[mapseq1.length - 1] = alignpos;
927 mapseq2[mapseq2.length - 1] = pdbpos;
929 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
931 jalview.datamodel.Mapping mapping = new Mapping(map);
937 * matches ochains against al and populates seqs with the best match between
938 * each ochain and the set in al
942 * @param dnaOrProtein
943 * @param removeOldAnnots
944 * when true, old annotation is cleared before new annotation
946 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
947 * List<AlignSeq> alignment between each>
949 public static List<List<? extends Object>> replaceMatchingSeqsWith(
950 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
951 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
952 boolean removeOldAnnots)
954 List<SequenceI> orig = new ArrayList<SequenceI>(),
955 repl = new ArrayList<SequenceI>();
956 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
957 if (al != null && al.getHeight() > 0)
959 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
960 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
962 for (SequenceI sq : ochains)
964 SequenceI bestm = null;
965 AlignSeq bestaseq = null;
967 for (SequenceI msq : al.getSequences())
969 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
970 if (bestm == null || aseq.getMaxScore() > bestscore)
972 bestscore = aseq.getMaxScore();
977 // System.out.println("Best Score for " + (matches.size() + 1) + " :"
980 aligns.add(bestaseq);
981 al.deleteSequence(bestm);
983 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
985 SequenceI sq, sp = seqs.get(p);
987 if ((q = ochains.indexOf(sp)) > -1)
989 seqs.set(p, sq = matches.get(q));
992 sq.setName(sp.getName());
993 sq.setDescription(sp.getDescription());
995 sq.transferAnnotation(sp,
996 sp2sq = aligns.get(q).getMappingFromS1(false));
997 aligs.add(aligns.get(q));
999 for (int ap = 0; ap < annotations.size();)
1001 if (annotations.get(ap).sequenceRef == sp)
1007 if (removeOldAnnots)
1009 annotations.remove(ap);
1013 AlignmentAnnotation alan = annotations.remove(ap);
1014 alan.liftOver(sq, sp2sq);
1015 alan.setSequenceRef(sq);
1016 sq.addAlignmentAnnotation(alan);
1024 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1026 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1027 Arrays.asList(sq.getAnnotation()));
1032 return Arrays.asList(orig, repl, aligs);
1036 * compute the PID vector used by the redundancy filter.
1038 * @param originalSequences
1039 * - sequences in alignment that are to filtered
1041 * - null or strings to be analysed (typically, visible portion of
1042 * each sequence in alignment)
1044 * - first column in window for calculation
1046 * - last column in window for calculation
1048 * - if true then use ungapped sequence to compute PID
1049 * @return vector containing maximum PID for i-th sequence and any sequences
1050 * longer than that seuqence
1052 public static float[] computeRedundancyMatrix(
1053 SequenceI[] originalSequences, String[] omitHidden, int start,
1054 int end, boolean ungapped)
1056 int height = originalSequences.length;
1057 float[] redundancy = new float[height];
1058 int[] lngth = new int[height];
1059 for (int i = 0; i < height; i++)
1065 // long start = System.currentTimeMillis();
1067 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1071 for (int i = 0; i < height; i++)
1074 for (int j = 0; j < i; j++)
1081 if (omitHidden == null)
1083 seqi = originalSequences[i].getSequenceAsString(start, end);
1084 seqj = originalSequences[j].getSequenceAsString(start, end);
1088 seqi = omitHidden[i];
1089 seqj = omitHidden[j];
1093 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1094 lngth[i] = ug.length();
1102 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1103 lngth[j] = ug.length();
1109 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1111 // use real sequence length rather than string length
1112 if (lngth[j] < lngth[i])
1114 redundancy[j] = Math.max(pid, redundancy[j]);
1118 redundancy[i] = Math.max(pid, redundancy[i]);