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.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.List;
42 import java.util.StringTokenizer;
52 public static final String PEP = "pep";
54 public static final String DNA = "dna";
56 private static final String NEWLINE = System.lineSeparator();
86 public String astr1 = "";
88 public String astr2 = "";
105 public float maxscore;
115 StringBuffer output = new StringBuffer();
117 String type; // AlignSeq.PEP or AlignSeq.DNA
119 private ScoreMatrix scoreMatrix;
121 private static final int GAP_INDEX = -1;
124 * Creates a new AlignSeq object.
127 * first sequence for alignment
129 * second sequence for alignment
131 * molecule type, either AlignSeq.PEP or AlignSeq.DNA
133 public AlignSeq(SequenceI s1, SequenceI s2, String type)
135 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
140 * Creates a new AlignSeq object.
149 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
150 String string2, String type)
152 seqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
158 * @return DOCUMENT ME!
160 public float getMaxScore()
168 * @return DOCUMENT ME!
170 public int getSeq2Start()
178 * @return DOCUMENT ME!
180 public int getSeq2End()
188 * @return DOCUMENT ME!
190 public int getSeq1Start()
198 * @return DOCUMENT ME!
200 public int getSeq1End()
208 * @return DOCUMENT ME!
210 public String getOutput()
212 return output.toString();
218 * @return DOCUMENT ME!
220 public String getAStr1()
228 * @return DOCUMENT ME!
230 public String getAStr2()
238 * @return DOCUMENT ME!
240 public int[] getASeq1()
248 * @return DOCUMENT ME!
250 public int[] getASeq2()
257 * @return aligned instance of Seq 1
259 public SequenceI getAlignedSeq1()
261 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
262 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
263 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
264 alSeq1.setDatasetSequence(
265 s1.getDatasetSequence() == null ? s1 : s1.getDatasetSequence());
271 * @return aligned instance of Seq 2
273 public SequenceI getAlignedSeq2()
275 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
276 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
277 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
278 alSeq2.setDatasetSequence(
279 s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence());
284 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
289 * - string to use for s1
293 * - string to use for s2
297 public void seqInit(SequenceI s1, String string1, SequenceI s2,
298 String string2, String type)
302 setDefaultParams(type);
303 seqInit(string1, string2);
307 * construct score matrix for string1 and string2 (after removing any existing
313 private void seqInit(String string1, String string2)
315 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
316 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
318 if (s1str.length() == 0 || s2str.length() == 0)
321 "ALL GAPS: " + (s1str.length() == 0 ? s1.getName() : " ")
322 + (s2str.length() == 0 ? s2.getName() : ""));
326 score = new float[s1str.length()][s2str.length()];
328 E = new float[s1str.length()][s2str.length()];
330 F = new float[s1str.length()][s2str.length()];
331 traceback = new int[s1str.length()][s2str.length()];
333 seq1 = indexEncode(s1str);
335 seq2 = indexEncode(s2str);
338 private void setDefaultParams(String moleculeType)
340 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
342 output.append("Wrong type = dna or pep only");
343 throw new Error(MessageManager
344 .formatMessage("error.unknown_type_dna_or_pep", new String[]
349 scoreMatrix = ScoreModels.getInstance()
350 .getDefaultModel(PEP.equals(type));
356 public void traceAlignment()
358 // Find the maximum score along the rhs or bottom row
359 float max = -Float.MAX_VALUE;
361 for (int i = 0; i < seq1.length; i++)
363 if (score[i][seq2.length - 1] > max)
365 max = score[i][seq2.length - 1];
367 maxj = seq2.length - 1;
371 for (int j = 0; j < seq2.length; j++)
373 if (score[seq1.length - 1][j] > max)
375 max = score[seq1.length - 1][j];
376 maxi = seq1.length - 1;
381 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
385 maxscore = score[i][j] / 10;
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(java.io.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 = s1.getName(), s2id = s2.getName();
460 int maxid = s1.getName().length();
461 if (s2.getName().length() > maxid)
463 maxid = s2.getName().length();
468 // JAL-527 - truncate the sequence ids
469 if (s1.getName().length() > maxid)
471 s1id = s1.getName().substring(0, 30);
473 if (s2.getName().length() > maxid)
475 s2id = s2.getName().substring(0, 30);
478 int len = 72 - maxid - 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 output.append(new Format("%" + maxid + "s").form(s1.getName()));
488 output.append(" : ").append(String.valueOf(s1.getStart()))
489 .append(" - ").append(String.valueOf(s1.getEnd()));
490 output.append(" (Sequence length = ")
491 .append(String.valueOf(s1str.length())).append(")")
493 output.append("Sequence ");
494 output.append(new Format("%" + maxid + "s").form(s2.getName()));
495 output.append(" : ").append(String.valueOf(s2.getStart()))
496 .append(" - ").append(String.valueOf(s2.getEnd()));
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(new Format("%" + (maxid) + "s").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(new Format("%" + (maxid) + "s").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 (type.equals("pep"))
539 if (pam250.getPairwiseScore(c1, c2) > 0)
555 // Now print the second aligned sequence
556 output = output.append(NEWLINE);
557 output = output.append(new Format("%" + (maxid) + "s").form(s2id))
560 for (int i = 0; i < len; i++)
562 if ((i + (j * len)) < astr2.length())
564 output.append(astr2.charAt(i + (j * len)));
568 output.append(NEWLINE).append(NEWLINE);
571 pid = pid / (aseq1.length - count) * 100;
572 output = output.append(new Format("Percentage ID = %2.2f\n").form(pid));
575 os.print(output.toString());
576 } catch (Exception ex)
589 * @return DOCUMENT ME!
591 public int findTrace(int i, int j)
594 // float pairwiseScore = lookup[seq1[i]][seq2[j]];
595 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
597 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
604 else if (F[i][j] == max)
618 else if (E[i][j] == max)
635 public void calcScoreMatrix()
640 // top left hand element
641 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
642 s2str.charAt(0)) * 10;
643 E[0][0] = -gapExtend;
646 // Calculate the top row first
647 for (int j = 1; j < m; j++)
649 // What should these values be? 0 maybe
650 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
651 F[0][j] = -gapExtend;
653 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
655 score[0][j] = max(pairwiseScore * 10, -gapOpen, -gapExtend);
660 // Now do the left hand column
661 for (int i = 1; i < n; i++)
664 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
666 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
668 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
669 traceback[i][0] = -1;
672 // Now do all the other rows
673 for (int i = 1; i < n; i++)
675 for (int j = 1; j < m; j++)
677 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
678 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
680 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
682 score[i][j] = max(score[i - 1][j - 1] + (pairwiseScore * 10),
684 traceback[i][j] = findTrace(i, j);
690 * Returns the given sequence with all of the given gap characters removed.
693 * a string of characters to be treated as gaps
699 public static String extractGaps(String gapChars, String seq)
701 if (gapChars == null || seq == null)
705 StringTokenizer str = new StringTokenizer(seq, gapChars);
706 StringBuilder newString = new StringBuilder(seq.length());
708 while (str.hasMoreTokens())
710 newString.append(str.nextToken());
713 return newString.toString();
726 * @return DOCUMENT ME!
728 private static float max(float f1, float f2, float f3)
753 * @return DOCUMENT ME!
755 private static float max(float f1, float f2)
768 * Converts the character string to an array of integers which are the
769 * corresponding indices to the characters in the score matrix
775 int[] indexEncode(String s)
777 int[] encoded = new int[s.length()];
779 for (int i = 0; i < s.length(); i++)
781 char c = s.charAt(i);
782 encoded[i] = scoreMatrix.getMatrixIndex(c);
802 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
805 // TODO method doesn't seem to be referenced anywhere delete??
809 for (int i = 0; i < n; i++)
811 for (int j = 0; j < m; j++)
813 if (mat[i][j] >= max)
818 if (mat[i][j] <= min)
825 System.out.println(max + " " + min);
827 for (int i = 0; i < n; i++)
829 for (int j = 0; j < m; j++)
834 // System.out.println(mat[i][j]);
835 float score = (float) (mat[i][j] - min) / (float) (max - min);
836 g.setColor(new Color(score, 0, 0));
837 g.fillRect(x, y, psize, psize);
839 // System.out.println(x + " " + y + " " + score);
845 * Compute a globally optimal needleman and wunsch alignment between two
851 * AlignSeq.DNA or AlignSeq.PEP
853 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
856 AlignSeq as = new AlignSeq(s1, s2, type);
858 as.calcScoreMatrix();
865 * @return mapping from positions in S1 to corresponding positions in S2
867 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
869 ArrayList<Integer> as1 = new ArrayList<Integer>(),
870 as2 = new ArrayList<Integer>();
871 int pdbpos = s2.getStart() + getSeq2Start() - 2;
872 int alignpos = s1.getStart() + getSeq1Start() - 2;
873 int lp2 = pdbpos - 3, lp1 = alignpos - 3;
874 boolean lastmatch = false;
875 // and now trace the alignment onto the atom set.
876 for (int i = 0; i < astr1.length(); i++)
878 char c1 = astr1.charAt(i), c2 = astr2.charAt(i);
889 if (allowmismatch || c1 == c2)
891 // extend mapping interval
892 if (lp1 + 1 != alignpos || lp2 + 1 != pdbpos)
894 as1.add(Integer.valueOf(alignpos));
895 as2.add(Integer.valueOf(pdbpos));
903 // extend mapping interval
906 as1.add(Integer.valueOf(lp1));
907 as2.add(Integer.valueOf(lp2));
912 // construct range pairs
914 int[] mapseq1 = new int[as1.size() + (lastmatch ? 1 : 0)],
915 mapseq2 = new int[as2.size() + (lastmatch ? 1 : 0)];
917 for (Integer ip : as1)
923 for (Integer ip : as2)
930 mapseq1[mapseq1.length - 1] = alignpos;
931 mapseq2[mapseq2.length - 1] = pdbpos;
933 MapList map = new MapList(mapseq1, mapseq2, 1, 1);
935 jalview.datamodel.Mapping mapping = new Mapping(map);
941 * matches ochains against al and populates seqs with the best match between
942 * each ochain and the set in al
946 * @param dnaOrProtein
947 * @param removeOldAnnots
948 * when true, old annotation is cleared before new annotation
950 * @return List<List<SequenceI> originals, List<SequenceI> replacement,
951 * List<AlignSeq> alignment between each>
953 public static List<List<? extends Object>> replaceMatchingSeqsWith(
954 List<SequenceI> seqs, List<AlignmentAnnotation> annotations,
955 List<SequenceI> ochains, AlignmentI al, String dnaOrProtein,
956 boolean removeOldAnnots)
958 List<SequenceI> orig = new ArrayList<SequenceI>(),
959 repl = new ArrayList<SequenceI>();
960 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
961 if (al != null && al.getHeight() > 0)
963 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
964 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
966 for (SequenceI sq : ochains)
968 SequenceI bestm = null;
969 AlignSeq bestaseq = null;
971 for (SequenceI msq : al.getSequences())
973 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
974 if (bestm == null || aseq.getMaxScore() > bestscore)
976 bestscore = aseq.getMaxScore();
981 // System.out.println("Best Score for " + (matches.size() + 1) + " :"
984 aligns.add(bestaseq);
985 al.deleteSequence(bestm);
987 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
989 SequenceI sq, sp = seqs.get(p);
991 if ((q = ochains.indexOf(sp)) > -1)
993 seqs.set(p, sq = matches.get(q));
996 sq.setName(sp.getName());
997 sq.setDescription(sp.getDescription());
999 sq.transferAnnotation(sp,
1000 sp2sq = aligns.get(q).getMappingFromS1(false));
1001 aligs.add(aligns.get(q));
1003 for (int ap = 0; ap < annotations.size();)
1005 if (annotations.get(ap).sequenceRef == sp)
1011 if (removeOldAnnots)
1013 annotations.remove(ap);
1017 AlignmentAnnotation alan = annotations.remove(ap);
1018 alan.liftOver(sq, sp2sq);
1019 alan.setSequenceRef(sq);
1020 sq.addAlignmentAnnotation(alan);
1028 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1030 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1031 Arrays.asList(sq.getAnnotation()));
1036 return Arrays.asList(orig, repl, aligs);
1040 * compute the PID vector used by the redundancy filter.
1042 * @param originalSequences
1043 * - sequences in alignment that are to filtered
1045 * - null or strings to be analysed (typically, visible portion of
1046 * each sequence in alignment)
1048 * - first column in window for calculation
1050 * - last column in window for calculation
1052 * - if true then use ungapped sequence to compute PID
1053 * @return vector containing maximum PID for i-th sequence and any sequences
1054 * longer than that seuqence
1056 public static float[] computeRedundancyMatrix(
1057 SequenceI[] originalSequences, String[] omitHidden, int start,
1058 int end, boolean ungapped)
1060 int height = originalSequences.length;
1061 float[] redundancy = new float[height];
1062 int[] lngth = new int[height];
1063 for (int i = 0; i < height; i++)
1069 // long start = System.currentTimeMillis();
1071 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1075 for (int i = 0; i < height; i++)
1078 for (int j = 0; j < i; j++)
1085 if (omitHidden == null)
1087 seqi = originalSequences[i].getSequenceAsString(start, end);
1088 seqj = originalSequences[j].getSequenceAsString(start, end);
1092 seqi = omitHidden[i];
1093 seqj = omitHidden[j];
1097 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1098 lngth[i] = ug.length();
1106 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1107 lngth[j] = ug.length();
1113 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1115 // use real sequence length rather than string length
1116 if (lngth[j] < lngth[i])
1118 redundancy[j] = Math.max(pid, redundancy[j]);
1122 redundancy[i] = Math.max(pid, redundancy[i]);