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.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AlignmentOrder;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.SequenceNode;
30 import jalview.util.Comparison;
31 import jalview.util.MessageManager;
32 import jalview.util.QuickSort;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.List;
39 * Routines for manipulating the order of a multiple sequence alignment TODO:
40 * this class retains some global states concerning sort-order which should be
41 * made attributes for the caller's alignment visualization. TODO: refactor to
42 * allow a subset of selected sequences to be sorted within the context of a
43 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
44 * data mapping to each tobesorted element to use ], Alignment context of
45 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
46 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
47 * resulting from applying the operation to tobesorted should be mapped back to
48 * the original positions in alignment. Otherwise, normal behaviour is to re
49 * order alignment so that tobesorted is sorted and grouped together starting
50 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
51 * becomes a,tb1,tb2,tb3,b,c)
53 public class AlignmentSorter
56 * todo: refactor searches to follow a basic pattern: (search property, last
57 * search state, current sort direction)
59 static boolean sortIdAscending = true;
61 static int lastGroupHash = 0;
63 static boolean sortGroupAscending = true;
65 static AlignmentOrder lastOrder = null;
67 static boolean sortOrderAscending = true;
69 static NJTree lastTree = null;
71 static boolean sortTreeAscending = true;
74 * last Annotation Label used by sortByScore
76 private static String lastSortByScore;
78 private static boolean sortByScoreAscending = true;
81 * compact representation of last arguments to SortByFeatureScore
83 private static String lastSortByFeatureScore;
85 private static boolean sortByFeatureScoreAscending = true;
87 private static boolean sortLengthAscending;
90 * Sort by Percentage Identity w.r.t. s
97 * sequences from align that are to be sorted.
99 public static void sortByPID(AlignmentI align, SequenceI s,
102 sortByPID(align, s, tosort, 0, -1);
106 * Sort by Percentage Identity w.r.t. s
113 * sequences from align that are to be sorted.
115 * start column (0 for beginning
118 public static void sortByPID(AlignmentI align, SequenceI s,
119 SequenceI[] tosort, int start, int end)
121 int nSeq = align.getHeight();
123 float[] scores = new float[nSeq];
124 SequenceI[] seqs = new SequenceI[nSeq];
126 for (int i = 0; i < nSeq; i++)
128 scores[i] = Comparison.PID(align.getSequenceAt(i)
129 .getSequenceAsString(), s.getSequenceAsString());
130 seqs[i] = align.getSequenceAt(i);
133 QuickSort.sort(scores, seqs);
135 setReverseOrder(align, seqs);
139 * Reverse the order of the sort
146 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
148 int nSeq = seqs.length;
158 len = (nSeq + 1) / 2;
161 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
163 synchronized (asq = align.getSequences())
165 for (int i = 0; i < len; i++)
167 // SequenceI tmp = seqs[i];
168 asq.set(i, seqs[nSeq - i - 1]);
169 asq.set(nSeq - i - 1, seqs[i]);
175 * Sets the Alignment object with the given sequences
178 * Alignment object to be updated
180 * sequences as a vector
182 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
184 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
188 * Sets the Alignment object with the given sequences
193 * sequences as an array
195 public static void setOrder(AlignmentI align, SequenceI[] seqs)
197 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
198 List<SequenceI> algn;
199 synchronized (algn = align.getSequences())
201 List<SequenceI> tmp = new ArrayList<SequenceI>();
203 for (int i = 0; i < seqs.length; i++)
205 if (algn.contains(seqs[i]))
212 // User may have hidden seqs, then clicked undo or redo
213 for (int i = 0; i < tmp.size(); i++)
215 algn.add(tmp.get(i));
221 * Sorts by ID. Numbers are sorted before letters.
224 * The alignment object to sort
226 public static void sortByID(AlignmentI align)
228 int nSeq = align.getHeight();
230 String[] ids = new String[nSeq];
231 SequenceI[] seqs = new SequenceI[nSeq];
233 for (int i = 0; i < nSeq; i++)
235 ids[i] = align.getSequenceAt(i).getName();
236 seqs[i] = align.getSequenceAt(i);
239 QuickSort.sort(ids, seqs);
243 setReverseOrder(align, seqs);
247 setOrder(align, seqs);
250 sortIdAscending = !sortIdAscending;
254 * Sorts by sequence length
257 * The alignment object to sort
259 public static void sortByLength(AlignmentI align)
261 int nSeq = align.getHeight();
263 float[] length = new float[nSeq];
264 SequenceI[] seqs = new SequenceI[nSeq];
266 for (int i = 0; i < nSeq; i++)
268 seqs[i] = align.getSequenceAt(i);
269 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
272 QuickSort.sort(length, seqs);
274 if (sortLengthAscending)
276 setReverseOrder(align, seqs);
280 setOrder(align, seqs);
283 sortLengthAscending = !sortLengthAscending;
287 * Sorts the alignment by size of group. <br>
288 * Maintains the order of sequences in each group by order in given alignment
292 * sorts the given alignment object by group
294 public static void sortByGroup(AlignmentI align)
296 // MAINTAINS ORIGNAL SEQUENCE ORDER,
297 // ORDERS BY GROUP SIZE
298 List<SequenceGroup> groups = new ArrayList<SequenceGroup>();
300 if (groups.hashCode() != lastGroupHash)
302 sortGroupAscending = true;
303 lastGroupHash = groups.hashCode();
307 sortGroupAscending = !sortGroupAscending;
310 // SORTS GROUPS BY SIZE
311 // ////////////////////
312 for (SequenceGroup sg : align.getGroups())
314 for (int j = 0; j < groups.size(); j++)
316 SequenceGroup sg2 = groups.get(j);
318 if (sg.getSize() > sg2.getSize())
326 if (!groups.contains(sg))
332 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
333 // /////////////////////////////////////////////
334 List<SequenceI> seqs = new ArrayList<SequenceI>();
336 for (int i = 0; i < groups.size(); i++)
338 SequenceGroup sg = groups.get(i);
339 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
341 for (int j = 0; j < orderedseqs.length; j++)
343 seqs.add(orderedseqs[j]);
347 if (sortGroupAscending)
349 setOrder(align, seqs);
353 setReverseOrder(align,
354 vectorSubsetToArray(seqs, align.getSequences()));
359 * Select sequences in order from tmp that is present in mask, and any
360 * remaining sequences in mask not in tmp
363 * thread safe collection of sequences
365 * thread safe collection of sequences
367 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
369 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
370 List<SequenceI> mask)
373 // tmp2 = tmp.retainAll(mask);
374 // return tmp2.addAll(mask.removeAll(tmp2))
376 ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
378 boolean[] tmask = new boolean[mask.size()];
380 for (i = 0; i < mask.size(); i++)
385 for (i = 0; i < tmp.size(); i++)
387 SequenceI sq = tmp.get(i);
388 idx = mask.indexOf(sq);
389 if (idx > -1 && tmask[idx])
396 for (i = 0; i < tmask.length; i++)
400 seqs.add(mask.get(i));
404 return seqs.toArray(new SequenceI[seqs.size()]);
408 * Sorts by a given AlignmentOrder object
413 * specified order for alignment
415 public static void sortBy(AlignmentI align, AlignmentOrder order)
417 // Get an ordered vector of sequences which may also be present in align
418 List<SequenceI> tmp = order.getOrder();
420 if (lastOrder == order)
422 sortOrderAscending = !sortOrderAscending;
426 sortOrderAscending = true;
429 if (sortOrderAscending)
431 setOrder(align, tmp);
435 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
447 * @return DOCUMENT ME!
449 private static List<SequenceI> getOrderByTree(AlignmentI align,
452 int nSeq = align.getHeight();
454 List<SequenceI> tmp = new ArrayList<SequenceI>();
456 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
458 if (tmp.size() != nSeq)
460 // TODO: JBPNote - decide if this is always an error
461 // (eg. not when a tree is associated to another alignment which has more
463 if (tmp.size() != nSeq)
465 addStrays(align, tmp);
468 if (tmp.size() != nSeq)
471 .println("WARNING: tmp.size()="
475 + " in getOrderByTree - tree contains sequences not in alignment");
483 * Sorts the alignment by a given tree
490 public static void sortByTree(AlignmentI align, NJTree tree)
492 List<SequenceI> tmp = getOrderByTree(align, tree);
494 // tmp should properly permute align with tree.
495 if (lastTree != tree)
497 sortTreeAscending = true;
502 sortTreeAscending = !sortTreeAscending;
505 if (sortTreeAscending)
507 setOrder(align, tmp);
511 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
523 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
525 int nSeq = align.getHeight();
527 for (int i = 0; i < nSeq; i++)
529 if (!tmp.contains(align.getSequenceAt(i)))
531 tmp.add(align.getSequenceAt(i));
535 if (nSeq != tmp.size())
538 .println("ERROR: Size still not right even after addStrays");
552 * @return DOCUMENT ME!
554 private static List<SequenceI> _sortByTree(SequenceNode node,
555 List<SequenceI> tmp, List<SequenceI> seqset)
562 SequenceNode left = (SequenceNode) node.left();
563 SequenceNode right = (SequenceNode) node.right();
565 if ((left == null) && (right == null))
567 if (!node.isPlaceholder() && (node.element() != null))
569 if (node.element() instanceof SequenceI)
571 if (!tmp.contains(node.element())) // && (seqset==null ||
572 // seqset.size()==0 ||
573 // seqset.contains(tmp)))
575 tmp.add((SequenceI) node.element());
584 _sortByTree(left, tmp, seqset);
585 _sortByTree(right, tmp, seqset);
592 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
597 * recover the order of sequences given by the safe numbering scheme introducd
598 * SeqsetUtils.uniquify.
600 public static void recoverOrder(SequenceI[] alignment)
602 float[] ids = new float[alignment.length];
604 for (int i = 0; i < alignment.length; i++)
606 ids[i] = (new Float(alignment[i].getName().substring(8)))
610 jalview.util.QuickSort.sort(ids, alignment);
614 * Sort sequence in order of increasing score attribute for annotation with a
615 * particular scoreLabel. Or reverse if same label was used previously
618 * exact label for sequence associated AlignmentAnnotation scores to
621 * sequences to be sorted
623 public static void sortByAnnotationScore(String scoreLabel,
624 AlignmentI alignment)
626 SequenceI[] seqs = alignment.getSequencesArray();
627 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
629 int hasScores = 0; // number of scores present on set
630 double[] scores = new double[seqs.length];
631 double min = 0, max = 0;
632 for (int i = 0; i < seqs.length; i++)
634 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
635 if (scoreAnn != null)
639 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
643 max = min = scores[i];
664 return; // do nothing - no scores present to sort by.
666 if (hasScores < seqs.length)
668 for (int i = 0; i < seqs.length; i++)
672 scores[i] = (max + i + 1.0);
677 jalview.util.QuickSort.sort(scores, seqs);
678 if (lastSortByScore != scoreLabel)
680 lastSortByScore = scoreLabel;
681 setOrder(alignment, seqs);
685 setReverseOrder(alignment, seqs);
690 * types of feature ordering: Sort by score : average score - or total score -
691 * over all features in region Sort by feature label text: (or if null -
692 * feature type text) - numerical or alphabetical Sort by feature density:
693 * based on counts - ignoring individual text or scores for each feature
695 public static String FEATURE_SCORE = "average_score";
697 public static String FEATURE_LABEL = "text";
699 public static String FEATURE_DENSITY = "density";
702 * sort the alignment using the features on each sequence found between start
703 * and stop with the given featureLabel (and optional group qualifier)
705 * @param featureLabel
710 * (-1 to include non-positional features)
712 * (-1 to only sort on non-positional features)
714 * - aligned sequences containing features
716 * - one of the string constants FEATURE_SCORE, FEATURE_LABEL,
719 public static void sortByFeature(String featureLabel, String groupLabel,
720 int start, int stop, AlignmentI alignment, String method)
722 sortByFeature(featureLabel == null ? null
723 : Arrays.asList(new String[] { featureLabel }),
724 groupLabel == null ? null
725 : Arrays.asList(new String[]{ groupLabel }), start, stop, alignment, method);
728 private static boolean containsIgnoreCase(final String lab,
729 final List<String> labs)
739 for (String label : labs)
741 if (lab.equalsIgnoreCase(label))
749 public static void sortByFeature(List<String> featureLabels,
750 List<String> groupLabels, int start, int stop, AlignmentI alignment,
753 if (method != FEATURE_SCORE && method != FEATURE_LABEL
754 && method != FEATURE_DENSITY)
758 .getString("error.implementation_error_sortbyfeature"));
761 boolean ignoreScore = method != FEATURE_SCORE;
762 StringBuffer scoreLabel = new StringBuffer();
763 scoreLabel.append(start + stop + method);
764 // This doesn't quite work yet - we'd like to have a canonical ordering that
765 // can be preserved from call to call
766 if (featureLabels != null)
768 for (String label : featureLabels)
770 scoreLabel.append(label);
773 if (groupLabels != null)
775 for (String label : groupLabels)
777 scoreLabel.append(label);
782 * if resorting the same feature, toggle sort order
784 if (lastSortByFeatureScore == null
785 || !scoreLabel.toString().equals(lastSortByFeatureScore))
787 sortByFeatureScoreAscending = true;
791 sortByFeatureScoreAscending = !sortByFeatureScoreAscending;
793 lastSortByFeatureScore = scoreLabel.toString();
795 SequenceI[] seqs = alignment.getSequencesArray();
797 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
799 int hasScores = 0; // number of scores present on set
800 double[] scores = new double[seqs.length];
801 int[] seqScores = new int[seqs.length];
802 Object[] feats = new Object[seqs.length];
803 double min = 0, max = 0;
804 for (int i = 0; i < seqs.length; i++)
806 SequenceFeature[] sf = seqs[i].getSequenceFeatures();
809 sf = new SequenceFeature[0];
813 SequenceFeature[] tmp = new SequenceFeature[sf.length];
814 for (int s = 0; s < tmp.length; s++)
820 int sstart = (start == -1) ? start : seqs[i].findPosition(start);
821 int sstop = (stop == -1) ? stop : seqs[i].findPosition(stop);
825 for (int f = 0; f < sf.length; f++)
827 // filter for selection criteria
829 // ignore features outwith alignment start-stop positions.
830 (sf[f].end < sstart || sf[f].begin > sstop) ||
831 // or ignore based on selection criteria
832 (featureLabels != null && !AlignmentSorter
833 .containsIgnoreCase(sf[f].type, featureLabels))
834 || (groupLabels != null
835 // problem here: we cannot eliminate null feature group features
836 && (sf[f].getFeatureGroup() != null && !AlignmentSorter
837 .containsIgnoreCase(sf[f].getFeatureGroup(),
840 // forget about this feature
846 // or, also take a look at the scores if necessary.
847 if (!ignoreScore && !Float.isNaN(sf[f].getScore()))
849 if (seqScores[i] == 0)
855 scores[i] += sf[f].getScore(); // take the first instance of this
860 SequenceFeature[] fs;
861 feats[i] = fs = new SequenceFeature[n];
865 for (int f = 0; f < sf.length; f++)
869 ((SequenceFeature[]) feats[i])[n++] = sf[f];
872 if (method == FEATURE_LABEL)
874 // order the labels by alphabet
875 String[] labs = new String[fs.length];
876 for (int l = 0; l < labs.length; l++)
878 labs[l] = (fs[l].getDescription() != null ? fs[l]
879 .getDescription() : fs[l].getType());
881 QuickSort.sort(labs, ((Object[]) feats[i]));
886 // compute average score
887 scores[i] /= seqScores[i];
888 // update the score bounds.
891 max = min = scores[i];
907 if (method == FEATURE_SCORE)
911 return; // do nothing - no scores present to sort by.
914 if (hasScores < seqs.length)
916 for (int i = 0; i < seqs.length; i++)
920 scores[i] = (max + 1 + i);
924 // int nf = (feats[i] == null) ? 0
925 // : ((SequenceFeature[]) feats[i]).length;
926 // // System.err.println("Sorting on Score: seq " +
928 // + " Feats: " + nf + " Score : " + scores[i]);
932 QuickSort.sortByDouble(scores, seqs, sortByFeatureScoreAscending);
934 else if (method == FEATURE_DENSITY)
936 for (int i = 0; i < seqs.length; i++)
938 int featureCount = feats[i] == null ? 0
939 : ((SequenceFeature[]) feats[i]).length;
940 scores[i] = featureCount;
941 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
942 // " Feats: "+featureCount+" Score : "+scores[i]);
944 QuickSort.sortByDouble(scores, seqs, sortByFeatureScoreAscending);
948 if (method == FEATURE_LABEL)
951 MessageManager.getString("error.not_yet_implemented"));
955 setOrder(alignment, seqs);