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.BinaryNode;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.datamodel.SequenceNode;
33 import jalview.util.QuickSort;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.Iterator;
38 import java.util.List;
41 * Routines for manipulating the order of a multiple sequence alignment TODO:
42 * this class retains some global states concerning sort-order which should be
43 * made attributes for the caller's alignment visualization. TODO: refactor to
44 * allow a subset of selected sequences to be sorted within the context of a
45 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
46 * data mapping to each tobesorted element to use ], Alignment context of
47 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
48 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
49 * resulting from applying the operation to tobesorted should be mapped back to
50 * the original positions in alignment. Otherwise, normal behaviour is to re
51 * order alignment so that tobesorted is sorted and grouped together starting
52 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
53 * becomes a,tb1,tb2,tb3,b,c)
55 public class AlignmentSorter
58 * todo: refactor searches to follow a basic pattern: (search property, last
59 * search state, current sort direction)
61 static boolean sortIdAscending = true;
63 static int lastGroupHash = 0;
65 static boolean sortGroupAscending = true;
67 static AlignmentOrder lastOrder = null;
69 static boolean sortOrderAscending = true;
71 static TreeModel lastTree = null;
73 static boolean sortTreeAscending = true;
76 * last Annotation Label used for sort by Annotation score
78 private static String lastSortByAnnotation;
81 * string hash of last arguments to sortByFeature
82 * (sort order toggles if this is unchanged between sorts)
84 private static String sortByFeatureCriteria;
86 private static boolean sortByFeatureAscending = true;
88 private static boolean sortLengthAscending;
91 * Sorts sequences in the alignment by Percentage Identity with the given
92 * reference sequence, sorting the highest identity to the top
100 public static void sortByPID(AlignmentI align, SequenceI s)
102 int nSeq = align.getHeight();
104 float[] scores = new float[nSeq];
105 SequenceI[] seqs = new SequenceI[nSeq];
106 String refSeq = s.getSequenceAsString();
108 SimilarityParams pidParams = new SimilarityParams(true, true, true,
110 for (int i = 0; i < nSeq; i++)
112 scores[i] = (float) PIDModel.computePID(
113 align.getSequenceAt(i).getSequenceAsString(), refSeq,
115 seqs[i] = align.getSequenceAt(i);
118 QuickSort.sort(scores, seqs);
120 setReverseOrder(align, seqs);
124 * Reverse the order of the sort
131 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
133 int nSeq = seqs.length;
143 len = (nSeq + 1) / 2;
146 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
147 List<SequenceI> asq = align.getSequences();
150 for (int i = 0; i < len; i++)
152 // SequenceI tmp = seqs[i];
153 asq.set(i, seqs[nSeq - i - 1]);
154 asq.set(nSeq - i - 1, seqs[i]);
160 * Sets the Alignment object with the given sequences
163 * Alignment object to be updated
165 * sequences as a vector
167 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
169 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
173 * Sets the Alignment object with the given sequences
178 * sequences as an array
180 public static void setOrder(AlignmentI align, SequenceI[] seqs)
182 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
183 List<SequenceI> algn = align.getSequences();
186 List<SequenceI> tmp = new ArrayList<>();
188 for (int i = 0; i < seqs.length; i++)
190 if (algn.contains(seqs[i]))
197 // User may have hidden seqs, then clicked undo or redo
198 for (int i = 0; i < tmp.size(); i++)
200 algn.add(tmp.get(i));
206 * Sorts by ID. Numbers are sorted before letters.
209 * The alignment object to sort
211 public static void sortByID(AlignmentI align)
213 int nSeq = align.getHeight();
215 String[] ids = new String[nSeq];
216 SequenceI[] seqs = new SequenceI[nSeq];
218 for (int i = 0; i < nSeq; i++)
220 ids[i] = align.getSequenceAt(i).getName();
221 seqs[i] = align.getSequenceAt(i);
224 QuickSort.sort(ids, seqs);
228 setReverseOrder(align, seqs);
232 setOrder(align, seqs);
235 sortIdAscending = !sortIdAscending;
239 * Sorts by sequence length
242 * The alignment object to sort
244 public static void sortByLength(AlignmentI align)
246 int nSeq = align.getHeight();
248 float[] length = new float[nSeq];
249 SequenceI[] seqs = new SequenceI[nSeq];
251 for (int i = 0; i < nSeq; i++)
253 seqs[i] = align.getSequenceAt(i);
254 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
257 QuickSort.sort(length, seqs);
259 if (sortLengthAscending)
261 setReverseOrder(align, seqs);
265 setOrder(align, seqs);
268 sortLengthAscending = !sortLengthAscending;
272 * Sorts the alignment by size of group. <br>
273 * Maintains the order of sequences in each group by order in given alignment
277 * sorts the given alignment object by group
279 public static void sortByGroup(AlignmentI align)
281 // MAINTAINS ORIGNAL SEQUENCE ORDER,
282 // ORDERS BY GROUP SIZE
283 List<SequenceGroup> groups = new ArrayList<>();
285 if (groups.hashCode() != lastGroupHash)
287 sortGroupAscending = true;
288 lastGroupHash = groups.hashCode();
292 sortGroupAscending = !sortGroupAscending;
295 // SORTS GROUPS BY SIZE
296 // ////////////////////
297 for (SequenceGroup sg : align.getGroups())
299 for (int j = 0; j < groups.size(); j++)
301 SequenceGroup sg2 = groups.get(j);
303 if (sg.getSize() > sg2.getSize())
311 if (!groups.contains(sg))
317 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
318 // /////////////////////////////////////////////
319 List<SequenceI> seqs = new ArrayList<>();
321 for (int i = 0; i < groups.size(); i++)
323 SequenceGroup sg = groups.get(i);
324 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
326 for (int j = 0; j < orderedseqs.length; j++)
328 seqs.add(orderedseqs[j]);
332 if (sortGroupAscending)
334 setOrder(align, seqs);
338 setReverseOrder(align,
339 vectorSubsetToArray(seqs, align.getSequences()));
344 * Select sequences in order from tmp that is present in mask, and any
345 * remaining sequences in mask not in tmp
348 * thread safe collection of sequences
350 * thread safe collection of sequences
352 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
354 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
355 List<SequenceI> mask)
358 // tmp2 = tmp.retainAll(mask);
359 // return tmp2.addAll(mask.removeAll(tmp2))
361 ArrayList<SequenceI> seqs = new ArrayList<>();
363 boolean[] tmask = new boolean[mask.size()];
365 for (i = 0; i < mask.size(); i++)
370 for (i = 0; i < tmp.size(); i++)
372 SequenceI sq = tmp.get(i);
373 idx = mask.indexOf(sq);
374 if (idx > -1 && tmask[idx])
381 for (i = 0; i < tmask.length; i++)
385 seqs.add(mask.get(i));
389 return seqs.toArray(new SequenceI[seqs.size()]);
393 * Sorts by a given AlignmentOrder object
398 * specified order for alignment
400 public static void sortBy(AlignmentI align, AlignmentOrder order)
402 // Get an ordered vector of sequences which may also be present in align
403 List<SequenceI> tmp = order.getOrder();
405 if (lastOrder == order)
407 sortOrderAscending = !sortOrderAscending;
411 sortOrderAscending = true;
414 if (sortOrderAscending)
416 setOrder(align, tmp);
420 setReverseOrder(align,
421 vectorSubsetToArray(tmp, align.getSequences()));
433 * @return DOCUMENT ME!
435 private static List<SequenceI> getOrderByTree(AlignmentI align,
438 int nSeq = align.getHeight();
440 List<SequenceI> tmp = new ArrayList<>();
442 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
444 if (tmp.size() != nSeq)
446 // TODO: JBPNote - decide if this is always an error
447 // (eg. not when a tree is associated to another alignment which has more
449 if (tmp.size() != nSeq)
451 addStrays(align, tmp);
454 if (tmp.size() != nSeq)
456 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
458 + " in getOrderByTree - tree contains sequences not in alignment");
466 * Sorts the alignment by a given tree
473 public static void sortByTree(AlignmentI align, TreeModel tree)
475 List<SequenceI> tmp = getOrderByTree(align, tree);
477 // tmp should properly permute align with tree.
478 if (lastTree != tree)
480 sortTreeAscending = true;
485 sortTreeAscending = !sortTreeAscending;
488 if (sortTreeAscending)
490 setOrder(align, tmp);
494 setReverseOrder(align,
495 vectorSubsetToArray(tmp, align.getSequences()));
507 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
509 int nSeq = align.getHeight();
511 for (int i = 0; i < nSeq; i++)
513 if (!tmp.contains(align.getSequenceAt(i)))
515 tmp.add(align.getSequenceAt(i));
519 if (nSeq != tmp.size())
522 .println("ERROR: Size still not right even after addStrays");
536 * @return DOCUMENT ME!
538 private static List<SequenceI> _sortByTree(BinaryNode node,
539 List<SequenceI> tmp, List<SequenceI> seqset)
546 BinaryNode left = (BinaryNode) node.left();
547 BinaryNode right = (BinaryNode) node.right();
549 if ((left == null) && (right == null))
551 if (!(node instanceof SequenceNode
552 && ((SequenceNode) node).isPlaceholder())
553 && (node.element() != null))
555 if (node.element() instanceof SequenceI)
557 if (!tmp.contains(node.element())) // && (seqset==null ||
558 // seqset.size()==0 ||
559 // seqset.contains(tmp)))
561 tmp.add((SequenceI) node.element());
570 _sortByTree(left, tmp, seqset);
571 _sortByTree(right, tmp, seqset);
578 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
583 * recover the order of sequences given by the safe numbering scheme introducd
584 * SeqsetUtils.uniquify.
586 public static void recoverOrder(SequenceI[] alignment)
588 float[] ids = new float[alignment.length];
590 for (int i = 0; i < alignment.length; i++)
592 ids[i] = (Float.valueOf(alignment[i].getName().substring(8)))
596 jalview.util.QuickSort.sort(ids, alignment);
600 * Sort sequence in order of increasing score attribute for annotation with a
601 * particular scoreLabel. Or reverse if same label was used previously
604 * exact label for sequence associated AlignmentAnnotation scores to
607 * sequences to be sorted
609 public static void sortByAnnotationScore(String scoreLabel,
610 AlignmentI alignment)
612 SequenceI[] seqs = alignment.getSequencesArray();
613 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
615 int hasScores = 0; // number of scores present on set
616 double[] scores = new double[seqs.length];
617 double min = 0, max = 0;
618 for (int i = 0; i < seqs.length; i++)
620 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
621 if (scoreAnn != null)
625 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
629 max = min = scores[i];
650 return; // do nothing - no scores present to sort by.
652 if (hasScores < seqs.length)
654 for (int i = 0; i < seqs.length; i++)
658 scores[i] = (max + i + 1.0);
663 jalview.util.QuickSort.sort(scores, seqs);
664 if (lastSortByAnnotation != scoreLabel)
666 lastSortByAnnotation = scoreLabel;
667 setOrder(alignment, seqs);
671 setReverseOrder(alignment, seqs);
676 * types of feature ordering: Sort by score : average score - or total score -
677 * over all features in region Sort by feature label text: (or if null -
678 * feature type text) - numerical or alphabetical Sort by feature density:
679 * based on counts - ignoring individual text or scores for each feature
681 public static String FEATURE_SCORE = "average_score";
683 public static String FEATURE_LABEL = "text";
685 public static String FEATURE_DENSITY = "density";
688 * Sort sequences by feature score or density, optionally restricted by
689 * feature types, feature groups, or alignment start/end positions.
691 * If the sort is repeated for the same combination of types and groups, sort
694 * @param featureTypes
695 * a list of feature types to include (or null for all)
697 * a list of feature groups to include (or null for all)
699 * start column position to include (base zero)
701 * end column position to include (base zero)
703 * the alignment to be sorted
705 * either "average_score" or "density" ("text" not yet implemented)
707 public static void sortByFeature(List<String> featureTypes,
708 List<String> groups, final int startCol, final int endCol,
709 AlignmentI alignment, String method)
711 if (method != FEATURE_SCORE && method != FEATURE_LABEL
712 && method != FEATURE_DENSITY)
714 String msg = String.format(
715 "Implementation Error - sortByFeature method must be either '%s' or '%s'",
716 FEATURE_SCORE, FEATURE_DENSITY);
717 System.err.println(msg);
721 flipFeatureSortIfUnchanged(method, featureTypes, groups, startCol,
724 SequenceI[] seqs = alignment.getSequencesArray();
726 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
728 int hasScores = 0; // number of scores present on set
729 double[] scores = new double[seqs.length];
730 int[] seqScores = new int[seqs.length];
731 Object[][] feats = new Object[seqs.length][];
735 for (int i = 0; i < seqs.length; i++)
738 * get sequence residues overlapping column region
739 * and features for residue positions and specified types
741 String[] types = featureTypes == null ? null
742 : featureTypes.toArray(new String[featureTypes.size()]);
743 List<SequenceFeature> sfs = seqs[i].findFeatures(startCol + 1,
749 Iterator<SequenceFeature> it = sfs.listIterator();
752 SequenceFeature sf = it.next();
755 * accept all features with null or empty group, otherwise
756 * check group is one of the currently visible groups
758 String featureGroup = sf.getFeatureGroup();
759 if (groups != null && featureGroup != null
760 && !"".equals(featureGroup)
761 && !groups.contains(featureGroup))
767 float score = sf.getScore();
768 if (FEATURE_SCORE.equals(method) && !Float.isNaN(score))
770 if (seqScores[i] == 0)
777 // take the first instance of this score // ??
782 feats[i] = sfs.toArray(new SequenceFeature[sfs.size()]);
785 if (method == FEATURE_LABEL)
787 // order the labels by alphabet (not yet implemented)
788 String[] labs = new String[sfs.size()];
789 for (int l = 0; l < sfs.size(); l++)
791 SequenceFeature sf = sfs.get(l);
792 String description = sf.getDescription();
793 labs[l] = (description != null ? description : sf.getType());
795 QuickSort.sort(labs, feats[i]);
800 // compute average score
801 scores[i] /= seqScores[i];
802 // update the score bounds.
810 max = Math.max(max, scores[i]);
811 min = Math.min(min, scores[i]);
816 if (FEATURE_SCORE.equals(method))
820 return; // do nothing - no scores present to sort by.
823 if (hasScores < seqs.length)
825 for (int i = 0; i < seqs.length; i++)
829 scores[i] = (max + 1 + i);
833 // int nf = (feats[i] == null) ? 0
834 // : ((SequenceFeature[]) feats[i]).length;
835 // // System.err.println("Sorting on Score: seq " +
837 // + " Feats: " + nf + " Score : " + scores[i]);
841 QuickSort.sortByDouble(scores, seqs, sortByFeatureAscending);
843 else if (FEATURE_DENSITY.equals(method))
845 for (int i = 0; i < seqs.length; i++)
847 int featureCount = feats[i] == null ? 0
848 : ((SequenceFeature[]) feats[i]).length;
849 scores[i] = featureCount;
850 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
851 // " Feats: "+featureCount+" Score : "+scores[i]);
853 QuickSort.sortByDouble(scores, seqs, sortByFeatureAscending);
856 setOrder(alignment, seqs);
860 * Builds a string hash of criteria for sorting, and if unchanged from last
861 * time, reverse the sort order
864 * @param featureTypes
869 protected static void flipFeatureSortIfUnchanged(String method,
870 List<String> featureTypes, List<String> groups,
871 final int startCol, final int endCol)
873 StringBuilder sb = new StringBuilder(64);
874 sb.append(startCol).append(method).append(endCol);
875 if (featureTypes != null)
877 Collections.sort(featureTypes);
878 sb.append(featureTypes.toString());
882 Collections.sort(groups);
883 sb.append(groups.toString());
885 String scoreCriteria = sb.toString();
888 * if resorting on the same criteria, toggle sort order
890 if (sortByFeatureCriteria == null
891 || !scoreCriteria.equals(sortByFeatureCriteria))
893 sortByFeatureAscending = true;
897 sortByFeatureAscending = !sortByFeatureAscending;
899 sortByFeatureCriteria = scoreCriteria;