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.SimilarityParams;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentOrder;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceGroup;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.SequenceNode;
32 import jalview.ext.treeviewer.TreeI;
33 import jalview.ext.treeviewer.TreeNodeI;
34 import jalview.util.QuickSort;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.Iterator;
39 import java.util.List;
43 * Routines for manipulating the order of a multiple sequence alignment TODO:
44 * this class retains some global states concerning sort-order which should be
45 * made attributes for the caller's alignment visualization. TODO: refactor to
46 * allow a subset of selected sequences to be sorted within the context of a
47 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
48 * data mapping to each tobesorted element to use ], Alignment context of
49 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
50 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
51 * resulting from applying the operation to tobesorted should be mapped back to
52 * the original positions in alignment. Otherwise, normal behaviour is to re
53 * order alignment so that tobesorted is sorted and grouped together starting
54 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
55 * becomes a,tb1,tb2,tb3,b,c)
57 public class AlignmentSorter
60 * todo: refactor searches to follow a basic pattern: (search property, last
61 * search state, current sort direction)
63 static boolean sortIdAscending = true;
65 static int lastGroupHash = 0;
67 static boolean sortGroupAscending = true;
69 static AlignmentOrder lastOrder = null;
71 static boolean sortOrderAscending = true;
73 static TreeModel lastTree = null;
75 static TreeI lastExternalTree = null;
77 static boolean sortTreeAscending = true;
80 * last Annotation Label used for sort by Annotation score
82 private static String lastSortByAnnotation;
85 * string hash of last arguments to sortByFeature
86 * (sort order toggles if this is unchanged between sorts)
88 private static String sortByFeatureCriteria;
90 private static boolean sortByFeatureAscending = true;
92 private static boolean sortLengthAscending;
95 * Sorts sequences in the alignment by Percentage Identity with the given
96 * reference sequence, sorting the highest identity to the top
104 public static void sortByPID(AlignmentI align, SequenceI s)
106 int nSeq = align.getHeight();
108 float[] scores = new float[nSeq];
109 SequenceI[] seqs = new SequenceI[nSeq];
110 String refSeq = s.getSequenceAsString();
112 SimilarityParams pidParams = new SimilarityParams(true, true, true,
114 for (int i = 0; i < nSeq; i++)
116 scores[i] = (float) PIDModel.computePID(
117 align.getSequenceAt(i).getSequenceAsString(), refSeq,
119 seqs[i] = align.getSequenceAt(i);
122 QuickSort.sort(scores, seqs);
124 setReverseOrder(align, seqs);
128 * Reverse the order of the sort
135 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
137 int nSeq = seqs.length;
147 len = (nSeq + 1) / 2;
150 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
152 synchronized (asq = align.getSequences())
154 for (int i = 0; i < len; i++)
156 // SequenceI tmp = seqs[i];
157 asq.set(i, seqs[nSeq - i - 1]);
158 asq.set(nSeq - i - 1, seqs[i]);
164 * Sets the Alignment object with the given sequences
167 * Alignment object to be updated
169 * sequences as a vector
171 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
173 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
177 * Sets the Alignment object with the given sequences
182 * sequences as an array
184 public static void setOrder(AlignmentI align, SequenceI[] seqs)
186 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
187 List<SequenceI> algn;
188 synchronized (algn = align.getSequences())
190 List<SequenceI> tmp = new ArrayList<>();
192 for (int i = 0; i < seqs.length; i++)
194 if (algn.contains(seqs[i]))
201 // User may have hidden seqs, then clicked undo or redo
202 for (int i = 0; i < tmp.size(); i++)
204 algn.add(tmp.get(i));
210 * Sorts by ID. Numbers are sorted before letters.
213 * The alignment object to sort
215 public static void sortByID(AlignmentI align)
217 int nSeq = align.getHeight();
219 String[] ids = new String[nSeq];
220 SequenceI[] seqs = new SequenceI[nSeq];
222 for (int i = 0; i < nSeq; i++)
224 ids[i] = align.getSequenceAt(i).getName();
225 seqs[i] = align.getSequenceAt(i);
228 QuickSort.sort(ids, seqs);
232 setReverseOrder(align, seqs);
236 setOrder(align, seqs);
239 sortIdAscending = !sortIdAscending;
243 * Sorts by sequence length
246 * The alignment object to sort
248 public static void sortByLength(AlignmentI align)
250 int nSeq = align.getHeight();
252 float[] length = new float[nSeq];
253 SequenceI[] seqs = new SequenceI[nSeq];
255 for (int i = 0; i < nSeq; i++)
257 seqs[i] = align.getSequenceAt(i);
258 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
261 QuickSort.sort(length, seqs);
263 if (sortLengthAscending)
265 setReverseOrder(align, seqs);
269 setOrder(align, seqs);
272 sortLengthAscending = !sortLengthAscending;
276 * Sorts the alignment by size of group. <br>
277 * Maintains the order of sequences in each group by order in given alignment
281 * sorts the given alignment object by group
283 public static void sortByGroup(AlignmentI align)
285 // MAINTAINS ORIGNAL SEQUENCE ORDER,
286 // ORDERS BY GROUP SIZE
287 List<SequenceGroup> groups = new ArrayList<>();
289 if (groups.hashCode() != lastGroupHash)
291 sortGroupAscending = true;
292 lastGroupHash = groups.hashCode();
296 sortGroupAscending = !sortGroupAscending;
299 // SORTS GROUPS BY SIZE
300 // ////////////////////
301 for (SequenceGroup sg : align.getGroups())
303 for (int j = 0; j < groups.size(); j++)
305 SequenceGroup sg2 = groups.get(j);
307 if (sg.getSize() > sg2.getSize())
315 if (!groups.contains(sg))
321 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
322 // /////////////////////////////////////////////
323 List<SequenceI> seqs = new ArrayList<>();
325 for (int i = 0; i < groups.size(); i++)
327 SequenceGroup sg = groups.get(i);
328 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
330 for (int j = 0; j < orderedseqs.length; j++)
332 seqs.add(orderedseqs[j]);
336 if (sortGroupAscending)
338 setOrder(align, seqs);
342 setReverseOrder(align,
343 vectorSubsetToArray(seqs, align.getSequences()));
348 * Select sequences in order from tmp that is present in mask, and any
349 * remaining sequences in mask not in tmp
352 * thread safe collection of sequences
354 * thread safe collection of sequences
356 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
358 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
359 List<SequenceI> mask)
362 // tmp2 = tmp.retainAll(mask);
363 // return tmp2.addAll(mask.removeAll(tmp2))
365 ArrayList<SequenceI> seqs = new ArrayList<>();
367 boolean[] tmask = new boolean[mask.size()];
369 for (i = 0; i < mask.size(); i++)
374 for (i = 0; i < tmp.size(); i++)
376 SequenceI sq = tmp.get(i);
377 idx = mask.indexOf(sq);
378 if (idx > -1 && tmask[idx])
385 for (i = 0; i < tmask.length; i++)
389 seqs.add(mask.get(i));
393 return seqs.toArray(new SequenceI[seqs.size()]);
397 * Sorts by a given AlignmentOrder object
402 * specified order for alignment
404 public static void sortBy(AlignmentI align, AlignmentOrder order)
406 // Get an ordered vector of sequences which may also be present in align
407 List<SequenceI> tmp = order.getOrder();
409 if (lastOrder == order)
411 sortOrderAscending = !sortOrderAscending;
415 sortOrderAscending = true;
418 if (sortOrderAscending)
420 setOrder(align, tmp);
424 setReverseOrder(align,
425 vectorSubsetToArray(tmp, align.getSequences()));
437 * @return DOCUMENT ME!
439 private static List<SequenceI> getOrderByTree(AlignmentI align,
442 int nSeq = align.getHeight();
444 List<SequenceI> tmp = new ArrayList<>();
446 tmp = _sortByTree(tree.getTopNode(), tmp);
448 if (tmp.size() != nSeq)
450 // TODO: JBPNote - decide if this is always an error
451 // (eg. not when a tree is associated to another alignment which has more
453 if (tmp.size() != nSeq)
455 addStrays(align, tmp);
458 if (tmp.size() != nSeq)
460 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
462 + " in getOrderByTree - tree contains sequences not in alignment");
471 private static List<SequenceI> getOrderByTree(TreeI aptxTree,
472 Map<TreeNodeI, SequenceI> nodesWithBoundSeqs)
474 List<SequenceI> seqsByTreeOrder = new ArrayList<>();
475 if (!aptxTree.isEmpty())
477 for (final Iterator<TreeNodeI> iter = aptxTree
478 .iterateInPreOrder(); iter.hasNext();)
480 TreeNodeI treeNode = iter.next();
481 seqsByTreeOrder.add(nodesWithBoundSeqs.get(treeNode));
485 return seqsByTreeOrder;
491 * Sorts the alignment by a given tree
498 public static void sortByTree(AlignmentI align, TreeModel tree)
500 List<SequenceI> tmp = getOrderByTree(align, tree);
502 // tmp should properly permute align with tree.
503 if (lastTree != tree)
505 sortTreeAscending = true;
510 sortTreeAscending = !sortTreeAscending;
513 if (sortTreeAscending)
515 setOrder(align, tmp);
519 setReverseOrder(align,
520 vectorSubsetToArray(tmp, align.getSequences()));
525 * Sorts the alignment by a given tree from Archaeopteryx
532 public static void sortByTree(AlignmentI align,
533 Map<TreeNodeI, SequenceI> nodesBoundToSequences,
534 TreeI treeI) throws IllegalArgumentException
536 List<SequenceI> tmp = getOrderByTree(treeI, nodesBoundToSequences);
540 if (lastExternalTree != treeI)
542 sortTreeAscending = true;
543 lastExternalTree = treeI;
547 sortTreeAscending = !sortTreeAscending;
550 if (sortTreeAscending)
552 setOrder(align, tmp);
556 setReverseOrder(align,
557 vectorSubsetToArray(tmp, align.getSequences()));
562 throw new IllegalArgumentException();
574 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
576 int nSeq = align.getHeight();
578 for (int i = 0; i < nSeq; i++)
580 if (!tmp.contains(align.getSequenceAt(i)))
582 tmp.add(align.getSequenceAt(i));
586 if (nSeq != tmp.size())
589 .println("ERROR: Size still not right even after addStrays");
603 * @return DOCUMENT ME!
605 private static List<SequenceI> _sortByTree(SequenceNode node,
613 SequenceNode left = (SequenceNode) node.left();
614 SequenceNode right = (SequenceNode) node.right();
616 if ((left == null) && (right == null))
618 if (!node.isPlaceholder() && (node.element() != null))
620 if (node.element() instanceof SequenceI)
622 if (!tmp.contains(node.element())) // && (seqset==null ||
623 // seqset.size()==0 ||
624 // seqset.contains(tmp)))
626 tmp.add((SequenceI) node.element());
635 _sortByTree(left, tmp);
636 _sortByTree(right, tmp);
645 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
650 * recover the order of sequences given by the safe numbering scheme introducd
651 * SeqsetUtils.uniquify.
653 public static void recoverOrder(SequenceI[] alignment)
655 float[] ids = new float[alignment.length];
657 for (int i = 0; i < alignment.length; i++)
659 ids[i] = (new Float(alignment[i].getName().substring(8)))
663 jalview.util.QuickSort.sort(ids, alignment);
667 * Sort sequence in order of increasing score attribute for annotation with a
668 * particular scoreLabel. Or reverse if same label was used previously
671 * exact label for sequence associated AlignmentAnnotation scores to
674 * sequences to be sorted
676 public static void sortByAnnotationScore(String scoreLabel,
677 AlignmentI alignment)
679 SequenceI[] seqs = alignment.getSequencesArray();
680 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
682 int hasScores = 0; // number of scores present on set
683 double[] scores = new double[seqs.length];
684 double min = 0, max = 0;
685 for (int i = 0; i < seqs.length; i++)
687 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
688 if (scoreAnn != null)
692 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
696 max = min = scores[i];
717 return; // do nothing - no scores present to sort by.
719 if (hasScores < seqs.length)
721 for (int i = 0; i < seqs.length; i++)
725 scores[i] = (max + i + 1.0);
730 jalview.util.QuickSort.sort(scores, seqs);
731 if (lastSortByAnnotation != scoreLabel)
733 lastSortByAnnotation = scoreLabel;
734 setOrder(alignment, seqs);
738 setReverseOrder(alignment, seqs);
743 * types of feature ordering: Sort by score : average score - or total score -
744 * over all features in region Sort by feature label text: (or if null -
745 * feature type text) - numerical or alphabetical Sort by feature density:
746 * based on counts - ignoring individual text or scores for each feature
748 public static String FEATURE_SCORE = "average_score";
750 public static String FEATURE_LABEL = "text";
752 public static String FEATURE_DENSITY = "density";
755 * Sort sequences by feature score or density, optionally restricted by
756 * feature types, feature groups, or alignment start/end positions.
758 * If the sort is repeated for the same combination of types and groups, sort
761 * @param featureTypes
762 * a list of feature types to include (or null for all)
764 * a list of feature groups to include (or null for all)
766 * start column position to include (base zero)
768 * end column position to include (base zero)
770 * the alignment to be sorted
772 * either "average_score" or "density" ("text" not yet implemented)
774 public static void sortByFeature(List<String> featureTypes,
775 List<String> groups, final int startCol, final int endCol,
776 AlignmentI alignment, String method)
778 if (method != FEATURE_SCORE && method != FEATURE_LABEL
779 && method != FEATURE_DENSITY)
782 .format("Implementation Error - sortByFeature method must be either '%s' or '%s'",
783 FEATURE_SCORE, FEATURE_DENSITY);
784 System.err.println(msg);
788 flipFeatureSortIfUnchanged(method, featureTypes, groups, startCol, endCol);
790 SequenceI[] seqs = alignment.getSequencesArray();
792 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
794 int hasScores = 0; // number of scores present on set
795 double[] scores = new double[seqs.length];
796 int[] seqScores = new int[seqs.length];
797 Object[][] feats = new Object[seqs.length][];
801 for (int i = 0; i < seqs.length; i++)
804 * get sequence residues overlapping column region
805 * and features for residue positions and specified types
807 String[] types = featureTypes == null ? null : featureTypes
808 .toArray(new String[featureTypes.size()]);
809 List<SequenceFeature> sfs = seqs[i].findFeatures(startCol + 1,
815 Iterator<SequenceFeature> it = sfs.listIterator();
818 SequenceFeature sf = it.next();
821 * accept all features with null or empty group, otherwise
822 * check group is one of the currently visible groups
824 String featureGroup = sf.getFeatureGroup();
825 if (groups != null && featureGroup != null
826 && !"".equals(featureGroup)
827 && !groups.contains(featureGroup))
833 float score = sf.getScore();
834 if (FEATURE_SCORE.equals(method) && !Float.isNaN(score))
836 if (seqScores[i] == 0)
843 // take the first instance of this score // ??
848 feats[i] = sfs.toArray(new SequenceFeature[sfs.size()]);
851 if (method == FEATURE_LABEL)
853 // order the labels by alphabet (not yet implemented)
854 String[] labs = new String[sfs.size()];
855 for (int l = 0; l < sfs.size(); l++)
857 SequenceFeature sf = sfs.get(l);
858 String description = sf.getDescription();
859 labs[l] = (description != null ? description : sf.getType());
861 QuickSort.sort(labs, feats[i]);
866 // compute average score
867 scores[i] /= seqScores[i];
868 // update the score bounds.
876 max = Math.max(max, scores[i]);
877 min = Math.min(min, scores[i]);
882 if (FEATURE_SCORE.equals(method))
886 return; // do nothing - no scores present to sort by.
889 if (hasScores < seqs.length)
891 for (int i = 0; i < seqs.length; i++)
895 scores[i] = (max + 1 + i);
899 // int nf = (feats[i] == null) ? 0
900 // : ((SequenceFeature[]) feats[i]).length;
901 // // System.err.println("Sorting on Score: seq " +
903 // + " Feats: " + nf + " Score : " + scores[i]);
907 QuickSort.sortByDouble(scores, seqs, sortByFeatureAscending);
909 else if (FEATURE_DENSITY.equals(method))
911 for (int i = 0; i < seqs.length; i++)
913 int featureCount = feats[i] == null ? 0
914 : ((SequenceFeature[]) feats[i]).length;
915 scores[i] = featureCount;
916 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
917 // " Feats: "+featureCount+" Score : "+scores[i]);
919 QuickSort.sortByDouble(scores, seqs, sortByFeatureAscending);
922 setOrder(alignment, seqs);
926 * Builds a string hash of criteria for sorting, and if unchanged from last
927 * time, reverse the sort order
930 * @param featureTypes
935 protected static void flipFeatureSortIfUnchanged(String method,
936 List<String> featureTypes, List<String> groups,
937 final int startCol, final int endCol)
939 StringBuilder sb = new StringBuilder(64);
940 sb.append(startCol).append(method).append(endCol);
941 if (featureTypes != null)
943 Collections.sort(featureTypes);
944 sb.append(featureTypes.toString());
948 Collections.sort(groups);
949 sb.append(groups.toString());
951 String scoreCriteria = sb.toString();
954 * if resorting on the same criteria, toggle sort order
956 if (sortByFeatureCriteria == null
957 || !scoreCriteria.equals(sortByFeatureCriteria))
959 sortByFeatureAscending = true;
963 sortByFeatureAscending = !sortByFeatureAscending;
965 sortByFeatureCriteria = scoreCriteria;