2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 package jalview.analysis;
23 import jalview.datamodel.*;
24 import jalview.util.*;
27 * Routines for manipulating the order of a multiple sequence alignment TODO:
28 * this class retains some global states concerning sort-order which should be
29 * made attributes for the caller's alignment visualization. TODO: refactor to
30 * allow a subset of selected sequences to be sorted within the context of a
31 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
32 * data mapping to each tobesorted element to use ], Alignment context of
33 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
34 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
35 * resulting from applying the operation to tobesorted should be mapped back to
36 * the original positions in alignment. Otherwise, normal behaviour is to re
37 * order alignment so that tobesorted is sorted and grouped together starting
38 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
39 * becomes a,tb1,tb2,tb3,b,c)
41 public class AlignmentSorter
43 static boolean sortIdAscending = true;
45 static int lastGroupHash = 0;
47 static boolean sortGroupAscending = true;
49 static AlignmentOrder lastOrder = null;
51 static boolean sortOrderAscending = true;
53 static NJTree lastTree = null;
55 static boolean sortTreeAscending = true;
58 * last Annotation Label used by sortByScore
60 private static String lastSortByScore;
63 * compact representation of last arguments to SortByFeatureScore
65 private static String lastSortByFeatureScore;
68 * Sort by Percentage Identity w.r.t. s
75 * sequences from align that are to be sorted.
77 public static void sortByPID(AlignmentI align, SequenceI s,
80 int nSeq = align.getHeight();
82 float[] scores = new float[nSeq];
83 SequenceI[] seqs = new SequenceI[nSeq];
85 for (int i = 0; i < nSeq; i++)
87 scores[i] = Comparison.PID(align.getSequenceAt(i)
88 .getSequenceAsString(), s.getSequenceAsString());
89 seqs[i] = align.getSequenceAt(i);
92 QuickSort.sort(scores, 0, scores.length - 1, seqs);
94 setReverseOrder(align, seqs);
98 * Reverse the order of the sort
105 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
107 int nSeq = seqs.length;
117 len = (nSeq + 1) / 2;
120 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
121 for (int i = 0; i < len; i++)
123 // SequenceI tmp = seqs[i];
124 align.getSequences().setElementAt(seqs[nSeq - i - 1], i);
125 align.getSequences().setElementAt(seqs[i], nSeq - i - 1);
130 * Sets the Alignment object with the given sequences
133 * Alignment object to be updated
135 * sequences as a vector
137 private static void setOrder(AlignmentI align, Vector tmp)
139 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
143 * Sets the Alignment object with the given sequences
148 * sequences as an array
150 public static void setOrder(AlignmentI align, SequenceI[] seqs)
152 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
153 Vector algn = align.getSequences();
154 Vector tmp = new Vector();
156 for (int i = 0; i < seqs.length; i++)
158 if (algn.contains(seqs[i]))
160 tmp.addElement(seqs[i]);
164 algn.removeAllElements();
165 // User may have hidden seqs, then clicked undo or redo
166 for (int i = 0; i < tmp.size(); i++)
168 algn.addElement(tmp.elementAt(i));
174 * Sorts by ID. Numbers are sorted before letters.
177 * The alignment object to sort
179 public static void sortByID(AlignmentI align)
181 int nSeq = align.getHeight();
183 String[] ids = new String[nSeq];
184 SequenceI[] seqs = new SequenceI[nSeq];
186 for (int i = 0; i < nSeq; i++)
188 ids[i] = align.getSequenceAt(i).getName();
189 seqs[i] = align.getSequenceAt(i);
192 QuickSort.sort(ids, seqs);
196 setReverseOrder(align, seqs);
200 setOrder(align, seqs);
203 sortIdAscending = !sortIdAscending;
207 * Sorts the alignment by size of group. <br>
208 * Maintains the order of sequences in each group by order in given alignment
212 * sorts the given alignment object by group
214 public static void sortByGroup(AlignmentI align)
216 // MAINTAINS ORIGNAL SEQUENCE ORDER,
217 // ORDERS BY GROUP SIZE
218 Vector groups = new Vector();
220 if (groups.hashCode() != lastGroupHash)
222 sortGroupAscending = true;
223 lastGroupHash = groups.hashCode();
227 sortGroupAscending = !sortGroupAscending;
230 // SORTS GROUPS BY SIZE
231 // ////////////////////
232 for (int i = 0; i < align.getGroups().size(); i++)
234 SequenceGroup sg = (SequenceGroup) align.getGroups().elementAt(i);
236 for (int j = 0; j < groups.size(); j++)
238 SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j);
240 if (sg.getSize() > sg2.getSize())
242 groups.insertElementAt(sg, j);
248 if (!groups.contains(sg))
250 groups.addElement(sg);
254 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
255 // /////////////////////////////////////////////
256 Vector seqs = new Vector();
258 for (int i = 0; i < groups.size(); i++)
260 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
261 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
263 for (int j = 0; j < orderedseqs.length; j++)
265 seqs.addElement(orderedseqs[j]);
269 if (sortGroupAscending)
271 setOrder(align, seqs);
275 setReverseOrder(align,
276 vectorSubsetToArray(seqs, align.getSequences()));
281 * Converts Vector to array. java 1.18 does not have Vector.toArray()
284 * Vector of SequenceI objects
286 * @return array of Sequence[]
288 private static SequenceI[] vectorToArray(Vector tmp)
290 SequenceI[] seqs = new SequenceI[tmp.size()];
292 for (int i = 0; i < tmp.size(); i++)
294 seqs[i] = (SequenceI) tmp.elementAt(i);
308 * @return DOCUMENT ME!
310 private static SequenceI[] vectorSubsetToArray(Vector tmp, Vector mask)
312 Vector seqs = new Vector();
314 boolean[] tmask = new boolean[mask.size()];
316 for (i = 0; i < mask.size(); i++)
321 for (i = 0; i < tmp.size(); i++)
323 Object sq = tmp.elementAt(i);
325 if (mask.contains(sq) && tmask[mask.indexOf(sq)])
327 tmask[mask.indexOf(sq)] = false;
332 for (i = 0; i < tmask.length; i++)
336 seqs.addElement(mask.elementAt(i));
340 return vectorToArray(seqs);
344 * Sorts by a given AlignmentOrder object
349 * specified order for alignment
351 public static void sortBy(AlignmentI align, AlignmentOrder order)
353 // Get an ordered vector of sequences which may also be present in align
354 Vector tmp = order.getOrder();
356 if (lastOrder == order)
358 sortOrderAscending = !sortOrderAscending;
362 sortOrderAscending = true;
365 if (sortOrderAscending)
367 setOrder(align, tmp);
371 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
383 * @return DOCUMENT ME!
385 private static Vector getOrderByTree(AlignmentI align, NJTree tree)
387 int nSeq = align.getHeight();
389 Vector tmp = new Vector();
391 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
393 if (tmp.size() != nSeq)
395 // TODO: JBPNote - decide if this is always an error
396 // (eg. not when a tree is associated to another alignment which has more
398 if (tmp.size() < nSeq)
400 addStrays(align, tmp);
403 if (tmp.size() != nSeq)
405 System.err.println("ERROR: tmp.size()=" + tmp.size() + " != nseq="
406 + nSeq + " in getOrderByTree");
414 * Sorts the alignment by a given tree
421 public static void sortByTree(AlignmentI align, NJTree tree)
423 Vector tmp = getOrderByTree(align, tree);
425 // tmp should properly permute align with tree.
426 if (lastTree != tree)
428 sortTreeAscending = true;
433 sortTreeAscending = !sortTreeAscending;
436 if (sortTreeAscending)
438 setOrder(align, tmp);
442 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
454 private static void addStrays(AlignmentI align, Vector seqs)
456 int nSeq = align.getHeight();
458 for (int i = 0; i < nSeq; i++)
460 if (!seqs.contains(align.getSequenceAt(i)))
462 seqs.addElement(align.getSequenceAt(i));
466 if (nSeq != seqs.size())
469 .println("ERROR: Size still not right even after addStrays");
483 * @return DOCUMENT ME!
485 private static Vector _sortByTree(SequenceNode node, Vector tmp,
493 SequenceNode left = (SequenceNode) node.left();
494 SequenceNode right = (SequenceNode) node.right();
496 if ((left == null) && (right == null))
498 if (!node.isPlaceholder() && (node.element() != null))
500 if (node.element() instanceof SequenceI)
502 if (!tmp.contains(node.element()))
504 tmp.addElement((SequenceI) node.element());
513 _sortByTree(left, tmp, seqset);
514 _sortByTree(right, tmp, seqset);
521 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
526 * recover the order of sequences given by the safe numbering scheme introducd
527 * SeqsetUtils.uniquify.
529 public static void recoverOrder(SequenceI[] alignment)
531 float[] ids = new float[alignment.length];
533 for (int i = 0; i < alignment.length; i++)
535 ids[i] = (new Float(alignment[i].getName().substring(8)))
539 jalview.util.QuickSort.sort(ids, alignment);
543 * Sort sequence in order of increasing score attribute for annotation with a
544 * particular scoreLabel. Or reverse if same label was used previously
547 * exact label for sequence associated AlignmentAnnotation
548 * scores to use for sorting.
550 * sequences to be sorted
552 public static void sortByAnnotationScore(String scoreLabel,
553 AlignmentI alignment)
555 SequenceI[] seqs = alignment.getSequencesArray();
556 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
558 int hasScores = 0; // number of scores present on set
559 double[] scores = new double[seqs.length];
560 double min = 0, max = 0;
561 for (int i = 0; i < seqs.length; i++)
563 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
564 if (scoreAnn != null)
568 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
572 max = min = scores[i];
593 return; // do nothing - no scores present to sort by.
595 if (hasScores < seqs.length)
597 for (int i = 0; i < seqs.length; i++)
601 scores[i] = (max + i+1.0);
606 jalview.util.QuickSort.sort(scores, seqs);
607 if (lastSortByScore != scoreLabel)
609 lastSortByScore = scoreLabel;
610 setOrder(alignment, seqs);
614 setReverseOrder(alignment, seqs);
618 * types of feature ordering:
619 * Sort by score : average score - or total score - over all features in region
620 * Sort by feature label text: (or if null - feature type text) - numerical or alphabetical
621 * Sort by feature density: based on counts - ignoring individual text or scores for each feature
623 public static String FEATURE_SCORE="average_score";
624 public static String FEATURE_LABEL="text";
625 public static String FEATURE_DENSITY="density";
628 * sort the alignment using the features on each sequence found between start and stop with the given featureLabel (and optional group qualifier)
629 * @param featureLabel (may not be null)
630 * @param groupLabel (may be null)
631 * @param start (-1 to include non-positional features)
632 * @param stop (-1 to only sort on non-positional features)
633 * @param alignment - aligned sequences containing features
634 * @param method - one of the string constants FEATURE_SCORE, FEATURE_LABEL, FEATURE_DENSITY
636 public static void sortByFeature(String featureLabel, String groupLabel, int start, int stop,
637 AlignmentI alignment, String method)
639 sortByFeature(featureLabel==null ? null : new String[] {featureLabel},
640 groupLabel==null ? null : new String[] {groupLabel}, start, stop, alignment, method);
642 private static boolean containsIgnoreCase(final String lab, final String[] labs)
652 for (int q=0;q<labs.length;q++)
654 if (labs[q]!=null && lab.equalsIgnoreCase(labs[q]))
661 public static void sortByFeature(String[] featureLabels, String[] groupLabels, int start, int stop,
662 AlignmentI alignment, String method)
664 if (method!=FEATURE_SCORE && method!=FEATURE_LABEL && method!=FEATURE_DENSITY)
666 throw new Error("Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY.");
668 boolean ignoreScore=method!=FEATURE_SCORE;
669 StringBuffer scoreLabel = new StringBuffer();
670 scoreLabel.append(start+stop+method);
671 // This doesn't work yet - we'd like to have a canonical ordering that can be preserved from call to call
672 for (int i=0;featureLabels!=null && i<featureLabels.length; i++)
674 scoreLabel.append(featureLabels[i]==null ? "null" : featureLabels[i]);
676 for (int i=0;groupLabels!=null && i<groupLabels.length; i++)
678 scoreLabel.append(groupLabels[i]==null ? "null" : groupLabels[i]);
680 SequenceI[] seqs = alignment.getSequencesArray();
682 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
684 int hasScores = 0; // number of scores present on set
685 double[] scores = new double[seqs.length];
686 int[] seqScores = new int[seqs.length];
687 Object[] feats = new Object[seqs.length];
688 double min = 0, max = 0;
689 for (int i = 0; i < seqs.length; i++)
691 SequenceFeature[] sf = seqs[i].getSequenceFeatures();
692 if (sf==null && seqs[i].getDatasetSequence()!=null)
694 sf = seqs[i].getDatasetSequence().getSequenceFeatures();
698 sf = new SequenceFeature[0];
700 SequenceFeature[] tmp = new SequenceFeature[sf.length];
701 for (int s=0; s<tmp.length;s++)
707 int sstart = (start==-1) ? start : seqs[i].findPosition(start);
708 int sstop = (stop==-1) ? stop : seqs[i].findPosition(stop);
712 for (int f=0;f<sf.length;f++)
714 // filter for selection criteria
716 // ignore features outwith alignment start-stop positions.
717 (sf[f].end < sstart || sf[f].begin > sstop)
719 // or ignore based on selection criteria
720 (featureLabels != null && !AlignmentSorter.containsIgnoreCase(sf[f].type, featureLabels))
721 || (groupLabels != null
722 // problem here: we cannot eliminate null feature group features
723 && (sf[f].getFeatureGroup() != null
724 && !AlignmentSorter.containsIgnoreCase(sf[f].getFeatureGroup(), groupLabels))))
726 // forget about this feature
730 // or, also take a look at the scores if necessary.
731 if (!ignoreScore && sf[f].getScore()!=Float.NaN)
739 scores[i] += sf[f].getScore(); // take the first instance of this
744 SequenceFeature[] fs;
745 feats[i] = fs = new SequenceFeature[n];
749 for (int f=0;f<sf.length;f++)
753 ((SequenceFeature[]) feats[i])[n++] = sf[f];
756 if (method==FEATURE_LABEL)
758 // order the labels by alphabet
759 String[] labs = new String[fs.length];
760 for (int l=0;l<labs.length; l++)
762 labs[l] = (fs[l].getDescription()!=null ? fs[l].getDescription() : fs[l].getType());
764 jalview.util.QuickSort.sort(labs, ((Object[]) feats[i]));
769 // compute average score
770 scores[i]/=seqScores[i];
771 // update the score bounds.
774 max = min = scores[i];
790 if (method==FEATURE_SCORE)
794 return; // do nothing - no scores present to sort by.
797 if (hasScores < seqs.length)
799 for (int i = 0; i < seqs.length; i++)
803 scores[i] = (max + i);
805 int nf=(feats[i]==null) ? 0 :((SequenceFeature[]) feats[i]).length;
806 System.err.println("Sorting on Score: seq "+seqs[i].getName()+ " Feats: "+nf+" Score : "+scores[i]);
811 jalview.util.QuickSort.sort(scores, seqs);
814 if (method==FEATURE_DENSITY)
817 // break ties between equivalent numbers for adjacent sequences by adding 1/Nseq*i on the original order
818 double fr = 0.9/(1.0*seqs.length);
819 for (int i=0;i<seqs.length; i++)
822 scores[i] = (0.05+fr*i)+(nf=((feats[i]==null) ? 0.0 :1.0*((SequenceFeature[]) feats[i]).length));
823 System.err.println("Sorting on Density: seq "+seqs[i].getName()+ " Feats: "+nf+" Score : "+scores[i]);
825 jalview.util.QuickSort.sort(scores, seqs);
828 if (method==FEATURE_LABEL)
830 throw new Error("Not yet implemented.");
833 if (lastSortByFeatureScore ==null || scoreLabel.equals(lastSortByFeatureScore))
835 setOrder(alignment, seqs);
839 setReverseOrder(alignment, seqs);
841 lastSortByFeatureScore = scoreLabel.toString();