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.
126 * @param s1 first sequence for alignment
127 * @param s2 second sequence for alignment
128 * @param type molecule type, either AlignSeq.PEP or AlignSeq.DNA
130 public AlignSeq(SequenceI s1, SequenceI s2, String type)
132 seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
137 * Creates a new AlignSeq object.
146 public AlignSeq(SequenceI s1, String string1, SequenceI s2,
147 String string2, String type)
149 seqInit(s1, string1.toUpperCase(), s2, string2.toUpperCase(), type);
155 * @return DOCUMENT ME!
157 public float getMaxScore()
165 * @return DOCUMENT ME!
167 public int getSeq2Start()
175 * @return DOCUMENT ME!
177 public int getSeq2End()
185 * @return DOCUMENT ME!
187 public int getSeq1Start()
195 * @return DOCUMENT ME!
197 public int getSeq1End()
205 * @return DOCUMENT ME!
207 public String getOutput()
209 return output.toString();
215 * @return DOCUMENT ME!
217 public String getAStr1()
225 * @return DOCUMENT ME!
227 public String getAStr2()
235 * @return DOCUMENT ME!
237 public int[] getASeq1()
245 * @return DOCUMENT ME!
247 public int[] getASeq2()
254 * @return aligned instance of Seq 1
256 public SequenceI getAlignedSeq1()
258 SequenceI alSeq1 = new Sequence(s1.getName(), getAStr1());
259 alSeq1.setStart(s1.getStart() + getSeq1Start() - 1);
260 alSeq1.setEnd(s1.getStart() + getSeq1End() - 1);
261 alSeq1.setDatasetSequence(s1.getDatasetSequence() == null ? s1 : s1
262 .getDatasetSequence());
268 * @return aligned instance of Seq 2
270 public SequenceI getAlignedSeq2()
272 SequenceI alSeq2 = new Sequence(s2.getName(), getAStr2());
273 alSeq2.setStart(s2.getStart() + getSeq2Start() - 1);
274 alSeq2.setEnd(s2.getStart() + getSeq2End() - 1);
275 alSeq2.setDatasetSequence(s2.getDatasetSequence() == null ? s2 : s2
276 .getDatasetSequence());
281 * Construct score matrix for sequences with standard DNA or PEPTIDE matrix
286 * - string to use for s1
290 * - string to use for s2
294 public void seqInit(SequenceI s1, String string1, SequenceI s2,
295 String string2, String type)
299 setDefaultParams(type);
300 seqInit(string1, string2);
304 * construct score matrix for string1 and string2 (after removing any existing
310 private void seqInit(String string1, String string2)
312 s1str = extractGaps(jalview.util.Comparison.GapChars, string1);
313 s2str = extractGaps(jalview.util.Comparison.GapChars, string2);
315 if (s1str.length() == 0 || s2str.length() == 0)
317 output.append("ALL GAPS: "
318 + (s1str.length() == 0 ? s1.getName() : " ")
319 + (s2str.length() == 0 ? s2.getName() : ""));
323 score = new float[s1str.length()][s2str.length()];
325 E = new float[s1str.length()][s2str.length()];
327 F = new float[s1str.length()][s2str.length()];
328 traceback = new int[s1str.length()][s2str.length()];
330 seq1 = indexEncode(s1str);
332 seq2 = indexEncode(s2str);
335 private void setDefaultParams(String moleculeType)
337 if (!PEP.equals(moleculeType) && !DNA.equals(moleculeType))
339 output.append("Wrong type = dna or pep only");
340 throw new Error(MessageManager.formatMessage(
341 "error.unknown_type_dna_or_pep",
342 new String[] { moleculeType }));
346 scoreMatrix = ScoreModels.getInstance().getDefaultModel(
353 public void traceAlignment()
355 // Find the maximum score along the rhs or bottom row
356 float max = -Float.MAX_VALUE;
358 for (int i = 0; i < seq1.length; i++)
360 if (score[i][seq2.length - 1] > max)
362 max = score[i][seq2.length - 1];
364 maxj = seq2.length - 1;
368 for (int j = 0; j < seq2.length; j++)
370 if (score[seq1.length - 1][j] > max)
372 max = score[seq1.length - 1][j];
373 maxi = seq1.length - 1;
378 // System.out.println(maxi + " " + maxj + " " + score[maxi][maxj]);
382 maxscore = score[i][j] / 10;
387 aseq1 = new int[seq1.length + seq2.length];
388 aseq2 = new int[seq1.length + seq2.length];
390 StringBuilder sb1 = new StringBuilder(aseq1.length);
391 StringBuilder sb2 = new StringBuilder(aseq2.length);
393 count = (seq1.length + seq2.length) - 1;
395 while (i > 0 && j > 0)
397 aseq1[count] = seq1[i];
398 sb1.append(s1str.charAt(i));
399 aseq2[count] = seq2[j];
400 sb2.append(s2str.charAt(j));
402 trace = findTrace(i, j);
412 aseq1[count] = GAP_INDEX;
413 sb1.replace(sb1.length() - 1, sb1.length(), "-");
415 else if (trace == -1)
418 aseq2[count] = GAP_INDEX;
419 sb2.replace(sb2.length() - 1, sb2.length(), "-");
428 if (aseq1[count] != GAP_INDEX)
430 aseq1[count] = seq1[i];
431 sb1.append(s1str.charAt(i));
434 if (aseq2[count] != GAP_INDEX)
436 aseq2[count] = seq2[j];
437 sb2.append(s2str.charAt(j));
441 * we built the character strings backwards, so now
442 * reverse them to convert to sequence strings
444 astr1 = sb1.reverse().toString();
445 astr2 = sb2.reverse().toString();
451 public void printAlignment(java.io.PrintStream os)
453 // TODO: Use original sequence characters rather than re-translated
454 // characters in output
455 // Find the biggest id length for formatting purposes
456 String s1id = s1.getName(), s2id = s2.getName();
457 int maxid = s1.getName().length();
458 if (s2.getName().length() > maxid)
460 maxid = s2.getName().length();
465 // JAL-527 - truncate the sequence ids
466 if (s1.getName().length() > maxid)
468 s1id = s1.getName().substring(0, 30);
470 if (s2.getName().length() > maxid)
472 s2id = s2.getName().substring(0, 30);
475 int len = 72 - maxid - 1;
476 int nochunks = ((aseq1.length - count) / len)
477 + ((aseq1.length - count) % len > 0 ? 1 : 0);
480 output.append("Score = ").append(score[maxi][maxj]).append(NEWLINE);
481 output.append("Length of alignment = ")
482 .append(String.valueOf(aseq1.length - count)).append(NEWLINE);
483 output.append("Sequence ");
484 output.append(new Format("%" + maxid + "s").form(s1.getName()));
485 output.append(" : ").append(String.valueOf(s1.getStart()))
486 .append(" - ").append(String.valueOf(s1.getEnd()));
487 output.append(" (Sequence length = ")
488 .append(String.valueOf(s1str.length())).append(")")
490 output.append("Sequence ");
491 output.append(new Format("%" + maxid + "s").form(s2.getName()));
492 output.append(" : ").append(String.valueOf(s2.getStart()))
493 .append(" - ").append(String.valueOf(s2.getEnd()));
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(new Format("%" + (maxid) + "s").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(new Format("%" + (maxid) + "s").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 (type.equals("pep"))
536 if (pam250.getPairwiseScore(c1, c2) > 0)
552 // Now print the second aligned sequence
553 output = output.append(NEWLINE);
554 output = output.append(new Format("%" + (maxid) + "s").form(s2id))
557 for (int i = 0; i < len; i++)
559 if ((i + (j * len)) < astr2.length())
561 output.append(astr2.charAt(i + (j * len)));
565 output.append(NEWLINE).append(NEWLINE);
568 pid = pid / (aseq1.length - count) * 100;
569 output = output.append(new Format("Percentage ID = %2.2f\n").form(pid));
572 os.print(output.toString());
573 } catch (Exception ex)
586 * @return DOCUMENT ME!
588 public int findTrace(int i, int j)
591 // float pairwiseScore = lookup[seq1[i]][seq2[j]];
592 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
594 float max = score[i - 1][j - 1] + (pairwiseScore * 10);
601 else if (F[i][j] == max)
615 else if (E[i][j] == max)
632 public void calcScoreMatrix()
637 // top left hand element
638 score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0),
639 s2str.charAt(0)) * 10;
640 E[0][0] = -gapExtend;
643 // Calculate the top row first
644 for (int j = 1; j < m; j++)
646 // What should these values be? 0 maybe
647 E[0][j] = max(score[0][j - 1] - gapOpen, E[0][j - 1] - gapExtend);
648 F[0][j] = -gapExtend;
650 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0),
652 score[0][j] = max(pairwiseScore * 10, -gapOpen, -gapExtend);
657 // Now do the left hand column
658 for (int i = 1; i < n; i++)
661 F[i][0] = max(score[i - 1][0] - gapOpen, F[i - 1][0] - gapExtend);
663 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
665 score[i][0] = max(pairwiseScore * 10, E[i][0], F[i][0]);
666 traceback[i][0] = -1;
669 // Now do all the other rows
670 for (int i = 1; i < n; i++)
672 for (int j = 1; j < m; j++)
674 E[i][j] = max(score[i][j - 1] - gapOpen, E[i][j - 1] - gapExtend);
675 F[i][j] = max(score[i - 1][j] - gapOpen, F[i - 1][j] - gapExtend);
677 float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(i),
679 score[i][j] = max(score[i - 1][j - 1]
680 + (pairwiseScore * 10), E[i][j], F[i][j]);
681 traceback[i][j] = findTrace(i, j);
687 * Returns the given sequence with all of the given gap characters removed.
690 * a string of characters to be treated as gaps
696 public static String extractGaps(String gapChars, String seq)
698 if (gapChars == null || seq == null)
702 StringTokenizer str = new StringTokenizer(seq, gapChars);
703 StringBuilder newString = new StringBuilder(seq.length());
705 while (str.hasMoreTokens())
707 newString.append(str.nextToken());
710 return newString.toString();
723 * @return DOCUMENT ME!
725 private static float max(float f1, float f2, float f3)
750 * @return DOCUMENT ME!
752 private static float max(float f1, float f2)
765 * Converts the character string to an array of integers which are the
766 * corresponding indices to the characters in the score matrix
772 int[] indexEncode(String s)
774 int[] encoded = new int[s.length()];
776 for (int i = 0; i < s.length(); i++)
778 char c = s.charAt(i);
779 encoded[i] = scoreMatrix.getMatrixIndex(c);
799 public static void displayMatrix(Graphics g, int[][] mat, int n, int m,
802 // TODO method doesn't seem to be referenced anywhere delete??
806 for (int i = 0; i < n; i++)
808 for (int j = 0; j < m; j++)
810 if (mat[i][j] >= max)
815 if (mat[i][j] <= min)
822 System.out.println(max + " " + min);
824 for (int i = 0; i < n; i++)
826 for (int j = 0; j < m; j++)
831 // System.out.println(mat[i][j]);
832 float score = (float) (mat[i][j] - min) / (float) (max - min);
833 g.setColor(new Color(score, 0, 0));
834 g.fillRect(x, y, psize, psize);
836 // System.out.println(x + " " + y + " " + score);
842 * Compute a globally optimal needleman and wunsch alignment between two
848 * AlignSeq.DNA or AlignSeq.PEP
850 public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2,
853 AlignSeq as = new AlignSeq(s1, s2, type);
855 as.calcScoreMatrix();
862 * @return mapping from positions in S1 to corresponding positions in S2
864 public jalview.datamodel.Mapping getMappingFromS1(boolean allowmismatch)
866 ArrayList<Integer> as1 = new ArrayList<Integer>(), 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)], mapseq2 = new int[as2
911 .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>(), repl = new ArrayList<SequenceI>();
955 List<AlignSeq> aligs = new ArrayList<AlignSeq>();
956 if (al != null && al.getHeight() > 0)
958 ArrayList<SequenceI> matches = new ArrayList<SequenceI>();
959 ArrayList<AlignSeq> aligns = new ArrayList<AlignSeq>();
961 for (SequenceI sq : ochains)
963 SequenceI bestm = null;
964 AlignSeq bestaseq = null;
966 for (SequenceI msq : al.getSequences())
968 AlignSeq aseq = doGlobalNWAlignment(msq, sq, dnaOrProtein);
969 if (bestm == null || aseq.getMaxScore() > bestscore)
971 bestscore = aseq.getMaxScore();
976 // System.out.println("Best Score for " + (matches.size() + 1) + " :"
979 aligns.add(bestaseq);
980 al.deleteSequence(bestm);
982 for (int p = 0, pSize = seqs.size(); p < pSize; p++)
984 SequenceI sq, sp = seqs.get(p);
986 if ((q = ochains.indexOf(sp)) > -1)
988 seqs.set(p, sq = matches.get(q));
991 sq.setName(sp.getName());
992 sq.setDescription(sp.getDescription());
994 sq.transferAnnotation(sp,
995 sp2sq = aligns.get(q).getMappingFromS1(false));
996 aligs.add(aligns.get(q));
998 for (int ap = 0; ap < annotations.size();)
1000 if (annotations.get(ap).sequenceRef == sp)
1006 if (removeOldAnnots)
1008 annotations.remove(ap);
1012 AlignmentAnnotation alan = annotations.remove(ap);
1013 alan.liftOver(sq, sp2sq);
1014 alan.setSequenceRef(sq);
1015 sq.addAlignmentAnnotation(alan);
1023 if (sq.getAnnotation() != null && sq.getAnnotation().length > 0)
1025 annotations.addAll(inspos == -1 ? annotations.size() : inspos,
1026 Arrays.asList(sq.getAnnotation()));
1031 return Arrays.asList(orig, repl, aligs);
1035 * compute the PID vector used by the redundancy filter.
1037 * @param originalSequences
1038 * - sequences in alignment that are to filtered
1040 * - null or strings to be analysed (typically, visible portion of
1041 * each sequence in alignment)
1043 * - first column in window for calculation
1045 * - last column in window for calculation
1047 * - if true then use ungapped sequence to compute PID
1048 * @return vector containing maximum PID for i-th sequence and any sequences
1049 * longer than that seuqence
1051 public static float[] computeRedundancyMatrix(
1052 SequenceI[] originalSequences, String[] omitHidden, int start,
1053 int end, boolean ungapped)
1055 int height = originalSequences.length;
1056 float[] redundancy = new float[height];
1057 int[] lngth = new int[height];
1058 for (int i = 0; i < height; i++)
1064 // long start = System.currentTimeMillis();
1066 SimilarityParams pidParams = new SimilarityParams(true, true, true,
1070 for (int i = 0; i < height; i++)
1073 for (int j = 0; j < i; j++)
1080 if (omitHidden == null)
1082 seqi = originalSequences[i].getSequenceAsString(start, end);
1083 seqj = originalSequences[j].getSequenceAsString(start, end);
1087 seqi = omitHidden[i];
1088 seqj = omitHidden[j];
1092 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqi);
1093 lngth[i] = ug.length();
1101 String ug = AlignSeq.extractGaps(Comparison.GapChars, seqj);
1102 lngth[j] = ug.length();
1108 pid = (float) PIDModel.computePID(seqi, seqj, pidParams);
1110 // use real sequence length rather than string length
1111 if (lngth[j] < lngth[i])
1113 redundancy[j] = Math.max(pid, redundancy[j]);
1117 redundancy[i] = Math.max(pid, redundancy[i]);