2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.analysis;
22 import jalview.datamodel.*;
23 import jalview.util.*;
26 * Routines for manipulating the order of a multiple sequence alignment TODO:
27 * this class retains some global states concerning sort-order which should be
28 * made attributes for the caller's alignment visualization. TODO: refactor to
29 * allow a subset of selected sequences to be sorted within the context of a
30 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
31 * data mapping to each tobesorted element to use ], Alignment context of
32 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
33 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
34 * resulting from applying the operation to tobesorted should be mapped back to
35 * the original positions in alignment. Otherwise, normal behaviour is to re
36 * order alignment so that tobesorted is sorted and grouped together starting
37 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
38 * becomes a,tb1,tb2,tb3,b,c)
40 public class AlignmentSorter
43 * todo: refactor searches to follow a basic pattern: (search property, last
44 * search state, current sort direction)
46 static boolean sortIdAscending = true;
48 static int lastGroupHash = 0;
50 static boolean sortGroupAscending = true;
52 static AlignmentOrder lastOrder = null;
54 static boolean sortOrderAscending = true;
56 static NJTree lastTree = null;
58 static boolean sortTreeAscending = true;
61 * last Annotation Label used by sortByScore
63 private static String lastSortByScore;
65 private static boolean sortByScoreAscending = true;
68 * compact representation of last arguments to SortByFeatureScore
70 private static String lastSortByFeatureScore;
72 private static boolean sortByFeatureScoreAscending = true;
74 private static boolean sortLengthAscending;
77 * Sort by Percentage Identity w.r.t. s
84 * sequences from align that are to be sorted.
86 public static void sortByPID(AlignmentI align, SequenceI s,
89 sortByPID(align, s, tosort, 0, -1);
93 * Sort by Percentage Identity w.r.t. s
100 * sequences from align that are to be sorted.
102 * start column (0 for beginning
105 public static void sortByPID(AlignmentI align, SequenceI s,
106 SequenceI[] tosort, int start, int end)
108 int nSeq = align.getHeight();
110 float[] scores = new float[nSeq];
111 SequenceI[] seqs = new SequenceI[nSeq];
113 for (int i = 0; i < nSeq; i++)
115 scores[i] = Comparison.PID(align.getSequenceAt(i)
116 .getSequenceAsString(), s.getSequenceAsString());
117 seqs[i] = align.getSequenceAt(i);
120 QuickSort.sort(scores, 0, scores.length - 1, seqs);
122 setReverseOrder(align, seqs);
126 * Reverse the order of the sort
133 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
135 int nSeq = seqs.length;
145 len = (nSeq + 1) / 2;
148 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
149 for (int i = 0; i < len; i++)
151 // SequenceI tmp = seqs[i];
152 align.getSequences().setElementAt(seqs[nSeq - i - 1], i);
153 align.getSequences().setElementAt(seqs[i], nSeq - i - 1);
158 * Sets the Alignment object with the given sequences
161 * Alignment object to be updated
163 * sequences as a vector
165 private static void setOrder(AlignmentI align, Vector tmp)
167 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
171 * Sets the Alignment object with the given sequences
176 * sequences as an array
178 public static void setOrder(AlignmentI align, SequenceI[] seqs)
180 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
181 Vector algn = align.getSequences();
182 Vector tmp = new Vector();
184 for (int i = 0; i < seqs.length; i++)
186 if (algn.contains(seqs[i]))
188 tmp.addElement(seqs[i]);
192 algn.removeAllElements();
193 // User may have hidden seqs, then clicked undo or redo
194 for (int i = 0; i < tmp.size(); i++)
196 algn.addElement(tmp.elementAt(i));
202 * Sorts by ID. Numbers are sorted before letters.
205 * The alignment object to sort
207 public static void sortByID(AlignmentI align)
209 int nSeq = align.getHeight();
211 String[] ids = new String[nSeq];
212 SequenceI[] seqs = new SequenceI[nSeq];
214 for (int i = 0; i < nSeq; i++)
216 ids[i] = align.getSequenceAt(i).getName();
217 seqs[i] = align.getSequenceAt(i);
220 QuickSort.sort(ids, seqs);
224 setReverseOrder(align, seqs);
228 setOrder(align, seqs);
231 sortIdAscending = !sortIdAscending;
235 * Sorts by sequence length
238 * The alignment object to sort
240 public static void sortByLength(AlignmentI align)
242 int nSeq = align.getHeight();
244 float[] length = new float[nSeq];
245 SequenceI[] seqs = new SequenceI[nSeq];
247 for (int i = 0; i < nSeq; i++)
249 seqs[i] = align.getSequenceAt(i);
250 length[i] = (float) (seqs[i].getEnd() - seqs[i].getStart());
253 QuickSort.sort(length, seqs);
255 if (sortLengthAscending)
257 setReverseOrder(align, seqs);
261 setOrder(align, seqs);
264 sortLengthAscending = !sortLengthAscending;
268 * Sorts the alignment by size of group. <br>
269 * Maintains the order of sequences in each group by order in given alignment
273 * sorts the given alignment object by group
275 public static void sortByGroup(AlignmentI align)
277 // MAINTAINS ORIGNAL SEQUENCE ORDER,
278 // ORDERS BY GROUP SIZE
279 Vector groups = new Vector();
281 if (groups.hashCode() != lastGroupHash)
283 sortGroupAscending = true;
284 lastGroupHash = groups.hashCode();
288 sortGroupAscending = !sortGroupAscending;
291 // SORTS GROUPS BY SIZE
292 // ////////////////////
293 for (SequenceGroup sg:align.getGroups())
295 for (int j = 0; j < groups.size(); j++)
297 SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j);
299 if (sg.getSize() > sg2.getSize())
301 groups.insertElementAt(sg, j);
307 if (!groups.contains(sg))
309 groups.addElement(sg);
313 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
314 // /////////////////////////////////////////////
315 Vector seqs = new Vector();
317 for (int i = 0; i < groups.size(); i++)
319 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
320 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
322 for (int j = 0; j < orderedseqs.length; j++)
324 seqs.addElement(orderedseqs[j]);
328 if (sortGroupAscending)
330 setOrder(align, seqs);
334 setReverseOrder(align,
335 vectorSubsetToArray(seqs, align.getSequences()));
340 * Converts Vector to array. java 1.18 does not have Vector.toArray()
343 * Vector of SequenceI objects
345 * @return array of Sequence[]
347 private static SequenceI[] vectorToArray(Vector tmp)
349 SequenceI[] seqs = new SequenceI[tmp.size()];
351 for (int i = 0; i < tmp.size(); i++)
353 seqs[i] = (SequenceI) tmp.elementAt(i);
367 * @return DOCUMENT ME!
369 private static SequenceI[] vectorSubsetToArray(Vector tmp, Vector mask)
371 Vector seqs = new Vector();
373 boolean[] tmask = new boolean[mask.size()];
375 for (i = 0; i < mask.size(); i++)
380 for (i = 0; i < tmp.size(); i++)
382 Object sq = tmp.elementAt(i);
383 idx = mask.indexOf(sq);
384 if (idx > -1 && tmask[idx])
391 for (i = 0; i < tmask.length; i++)
395 seqs.addElement(mask.elementAt(i));
399 return vectorToArray(seqs);
403 * Sorts by a given AlignmentOrder object
408 * specified order for alignment
410 public static void sortBy(AlignmentI align, AlignmentOrder order)
412 // Get an ordered vector of sequences which may also be present in align
413 Vector tmp = order.getOrder();
415 if (lastOrder == order)
417 sortOrderAscending = !sortOrderAscending;
421 sortOrderAscending = true;
424 if (sortOrderAscending)
426 setOrder(align, tmp);
430 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
442 * @return DOCUMENT ME!
444 private static Vector getOrderByTree(AlignmentI align, NJTree tree)
446 int nSeq = align.getHeight();
448 Vector tmp = new Vector();
450 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
452 if (tmp.size() != nSeq)
454 // TODO: JBPNote - decide if this is always an error
455 // (eg. not when a tree is associated to another alignment which has more
457 if (tmp.size() != nSeq)
459 addStrays(align, tmp);
462 if (tmp.size() != nSeq)
464 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
465 + nSeq + " in getOrderByTree - tree contains sequences not in alignment");
473 * Sorts the alignment by a given tree
480 public static void sortByTree(AlignmentI align, NJTree tree)
482 Vector tmp = getOrderByTree(align, tree);
484 // tmp should properly permute align with tree.
485 if (lastTree != tree)
487 sortTreeAscending = true;
492 sortTreeAscending = !sortTreeAscending;
495 if (sortTreeAscending)
497 setOrder(align, tmp);
501 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
513 private static void addStrays(AlignmentI align, Vector seqs)
515 int nSeq = align.getHeight();
517 for (int i = 0; i < nSeq; i++)
519 if (!seqs.contains(align.getSequenceAt(i)))
521 seqs.addElement(align.getSequenceAt(i));
525 if (nSeq != seqs.size())
528 .println("ERROR: Size still not right even after addStrays");
542 * @return DOCUMENT ME!
544 private static Vector _sortByTree(SequenceNode node, Vector tmp,
552 SequenceNode left = (SequenceNode) node.left();
553 SequenceNode right = (SequenceNode) node.right();
555 if ((left == null) && (right == null))
557 if (!node.isPlaceholder() && (node.element() != null))
559 if (node.element() instanceof SequenceI)
561 if (!tmp.contains(node.element())) // && (seqset==null || seqset.size()==0 || seqset.contains(tmp)))
563 tmp.addElement((SequenceI) node.element());
572 _sortByTree(left, tmp, seqset);
573 _sortByTree(right, tmp, seqset);
580 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
585 * recover the order of sequences given by the safe numbering scheme introducd
586 * SeqsetUtils.uniquify.
588 public static void recoverOrder(SequenceI[] alignment)
590 float[] ids = new float[alignment.length];
592 for (int i = 0; i < alignment.length; i++)
594 ids[i] = (new Float(alignment[i].getName().substring(8)))
598 jalview.util.QuickSort.sort(ids, alignment);
602 * Sort sequence in order of increasing score attribute for annotation with a
603 * particular scoreLabel. Or reverse if same label was used previously
606 * exact label for sequence associated AlignmentAnnotation scores to
609 * sequences to be sorted
611 public static void sortByAnnotationScore(String scoreLabel,
612 AlignmentI alignment)
614 SequenceI[] seqs = alignment.getSequencesArray();
615 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
617 int hasScores = 0; // number of scores present on set
618 double[] scores = new double[seqs.length];
619 double min = 0, max = 0;
620 for (int i = 0; i < seqs.length; i++)
622 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
623 if (scoreAnn != null)
627 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
631 max = min = scores[i];
652 return; // do nothing - no scores present to sort by.
654 if (hasScores < seqs.length)
656 for (int i = 0; i < seqs.length; i++)
660 scores[i] = (max + i + 1.0);
665 jalview.util.QuickSort.sort(scores, seqs);
666 if (lastSortByScore != scoreLabel)
668 lastSortByScore = scoreLabel;
669 setOrder(alignment, seqs);
673 setReverseOrder(alignment, seqs);
678 * types of feature ordering: Sort by score : average score - or total score -
679 * over all features in region Sort by feature label text: (or if null -
680 * feature type text) - numerical or alphabetical Sort by feature density:
681 * based on counts - ignoring individual text or scores for each feature
683 public static String FEATURE_SCORE = "average_score";
685 public static String FEATURE_LABEL = "text";
687 public static String FEATURE_DENSITY = "density";
690 * sort the alignment using the features on each sequence found between start
691 * and stop with the given featureLabel (and optional group qualifier)
693 * @param featureLabel
698 * (-1 to include non-positional features)
700 * (-1 to only sort on non-positional features)
702 * - aligned sequences containing features
704 * - one of the string constants FEATURE_SCORE, FEATURE_LABEL,
707 public static void sortByFeature(String featureLabel, String groupLabel,
708 int start, int stop, AlignmentI alignment, String method)
710 sortByFeature(featureLabel == null ? null : new String[]
711 { featureLabel }, groupLabel == null ? null : new String[]
712 { groupLabel }, start, stop, alignment, method);
715 private static boolean containsIgnoreCase(final String lab,
726 for (int q = 0; q < labs.length; q++)
728 if (labs[q] != null && lab.equalsIgnoreCase(labs[q]))
736 public static void sortByFeature(String[] featureLabels,
737 String[] groupLabels, int start, int stop, AlignmentI alignment,
740 if (method != FEATURE_SCORE && method != FEATURE_LABEL
741 && method != FEATURE_DENSITY)
744 "Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY.");
746 boolean ignoreScore = method != FEATURE_SCORE;
747 StringBuffer scoreLabel = new StringBuffer();
748 scoreLabel.append(start + stop + method);
749 // This doesn't quite work yet - we'd like to have a canonical ordering that
750 // can be preserved from call to call
751 for (int i = 0; featureLabels != null && i < featureLabels.length; i++)
753 scoreLabel.append(featureLabels[i] == null ? "null"
756 for (int i = 0; groupLabels != null && i < groupLabels.length; i++)
758 scoreLabel.append(groupLabels[i] == null ? "null" : groupLabels[i]);
760 SequenceI[] seqs = alignment.getSequencesArray();
762 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
764 int hasScores = 0; // number of scores present on set
765 double[] scores = new double[seqs.length];
766 int[] seqScores = new int[seqs.length];
767 Object[] feats = new Object[seqs.length];
768 double min = 0, max = 0;
769 for (int i = 0; i < seqs.length; i++)
771 SequenceFeature[] sf = seqs[i].getSequenceFeatures();
772 if (sf == null && seqs[i].getDatasetSequence() != null)
774 sf = seqs[i].getDatasetSequence().getSequenceFeatures();
778 sf = new SequenceFeature[0];
782 SequenceFeature[] tmp = new SequenceFeature[sf.length];
783 for (int s = 0; s < tmp.length; s++)
789 int sstart = (start == -1) ? start : seqs[i].findPosition(start);
790 int sstop = (stop == -1) ? stop : seqs[i].findPosition(stop);
794 for (int f = 0; f < sf.length; f++)
796 // filter for selection criteria
798 // ignore features outwith alignment start-stop positions.
799 (sf[f].end < sstart || sf[f].begin > sstop) ||
800 // or ignore based on selection criteria
801 (featureLabels != null && !AlignmentSorter
802 .containsIgnoreCase(sf[f].type, featureLabels))
803 || (groupLabels != null
804 // problem here: we cannot eliminate null feature group features
805 && (sf[f].getFeatureGroup() != null && !AlignmentSorter
806 .containsIgnoreCase(sf[f].getFeatureGroup(),
809 // forget about this feature
815 // or, also take a look at the scores if necessary.
816 if (!ignoreScore && sf[f].getScore() != Float.NaN)
818 if (seqScores[i] == 0)
824 scores[i] += sf[f].getScore(); // take the first instance of this
829 SequenceFeature[] fs;
830 feats[i] = fs = new SequenceFeature[n];
834 for (int f = 0; f < sf.length; f++)
838 ((SequenceFeature[]) feats[i])[n++] = sf[f];
841 if (method == FEATURE_LABEL)
843 // order the labels by alphabet
844 String[] labs = new String[fs.length];
845 for (int l = 0; l < labs.length; l++)
847 labs[l] = (fs[l].getDescription() != null ? fs[l]
848 .getDescription() : fs[l].getType());
850 jalview.util.QuickSort.sort(labs, ((Object[]) feats[i]));
855 // compute average score
856 scores[i] /= seqScores[i];
857 // update the score bounds.
860 max = min = scores[i];
876 if (method == FEATURE_SCORE)
880 return; // do nothing - no scores present to sort by.
883 if (hasScores < seqs.length)
885 for (int i = 0; i < seqs.length; i++)
889 scores[i] = (max + 1 + i);
893 int nf = (feats[i] == null) ? 0
894 : ((SequenceFeature[]) feats[i]).length;
895 // System.err.println("Sorting on Score: seq "+seqs[i].getName()+
896 // " Feats: "+nf+" Score : "+scores[i]);
901 jalview.util.QuickSort.sort(scores, seqs);
903 else if (method == FEATURE_DENSITY)
906 // break ties between equivalent numbers for adjacent sequences by adding
907 // 1/Nseq*i on the original order
908 double fr = 0.9 / (1.0 * seqs.length);
909 for (int i = 0; i < seqs.length; i++)
912 scores[i] = (0.05 + fr * i)
913 + (nf = ((feats[i] == null) ? 0.0
914 : 1.0 * ((SequenceFeature[]) feats[i]).length));
915 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
916 // " Feats: "+nf+" Score : "+scores[i]);
918 jalview.util.QuickSort.sort(scores, seqs);
922 if (method == FEATURE_LABEL)
924 throw new Error("Not yet implemented.");
927 if (lastSortByFeatureScore == null
928 || !scoreLabel.toString().equals(lastSortByFeatureScore))
930 sortByFeatureScoreAscending = true;
934 sortByFeatureScoreAscending = !sortByFeatureScoreAscending;
936 if (sortByFeatureScoreAscending)
938 setOrder(alignment, seqs);
942 setReverseOrder(alignment, seqs);
944 lastSortByFeatureScore = scoreLabel.toString();