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.bin.ApplicationSingletonProvider;
26 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AlignmentOrder;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.datamodel.SequenceNode;
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;
42 * Routines for manipulating the order of a multiple sequence alignment TODO:
43 * this class retains some global states concerning sort-order which should be
44 * made attributes for the caller's alignment visualization. TODO: refactor to
45 * allow a subset of selected sequences to be sorted within the context of a
46 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
47 * data mapping to each tobesorted element to use ], Alignment context of
48 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
49 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
50 * resulting from applying the operation to tobesorted should be mapped back to
51 * the original positions in alignment. Otherwise, normal behaviour is to re
52 * order alignment so that tobesorted is sorted and grouped together starting
53 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
54 * becomes a,tb1,tb2,tb3,b,c)
56 public class AlignmentSorter implements ApplicationSingletonI
59 private AlignmentSorter()
64 private static AlignmentSorter getInstance()
66 return (AlignmentSorter) ApplicationSingletonProvider
67 .getInstance(AlignmentSorter.class);
71 * types of feature ordering: Sort by score : average score - or total score -
72 * over all features in region Sort by feature label text: (or if null -
73 * feature type text) - numerical or alphabetical Sort by feature density:
74 * based on counts - ignoring individual text or scores for each feature
76 public static final String FEATURE_SCORE = "average_score";
78 public static final String FEATURE_LABEL = "text";
80 public static final String FEATURE_DENSITY = "density";
83 * todo: refactor searches to follow a basic pattern: (search property, last
84 * search state, current sort direction)
86 boolean sortIdAscending = true;
88 int lastGroupHash = 0;
90 boolean sortGroupAscending = true;
92 AlignmentOrder lastOrder = null;
94 boolean sortOrderAscending = true;
96 TreeModel lastTree = null;
98 boolean sortTreeAscending = true;
102 * last Annotation Label used for sort by Annotation score
104 private String lastSortByAnnotation;
107 * string hash of last arguments to sortByFeature (sort order toggles if this
108 * is unchanged between sorts)
110 private String sortByFeatureCriteria;
112 private boolean sortByFeatureAscending = true;
114 private boolean sortLengthAscending;
117 * Sorts sequences in the alignment by Percentage Identity with the given
118 * reference sequence, sorting the highest identity to the top
126 public static void sortByPID(AlignmentI align, SequenceI s)
128 int nSeq = align.getHeight();
130 float[] scores = new float[nSeq];
131 SequenceI[] seqs = new SequenceI[nSeq];
132 String refSeq = s.getSequenceAsString();
134 SimilarityParams pidParams = new SimilarityParams(true, true, true,
136 for (int i = 0; i < nSeq; i++)
138 scores[i] = (float) PIDModel.computePID(
139 align.getSequenceAt(i).getSequenceAsString(), refSeq,
141 seqs[i] = align.getSequenceAt(i);
144 QuickSort.sort(scores, seqs);
146 setReverseOrder(align, seqs);
150 * Reverse the order of the sort
157 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
159 int nSeq = seqs.length;
169 len = (nSeq + 1) / 2;
172 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
173 List<SequenceI> asq = align.getSequences();
176 for (int i = 0; i < len; i++)
178 // SequenceI tmp = seqs[i];
179 asq.set(i, seqs[nSeq - i - 1]);
180 asq.set(nSeq - i - 1, seqs[i]);
186 * Sets the Alignment object with the given sequences
189 * Alignment object to be updated
191 * sequences as a vector
193 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
195 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
199 * Sets the Alignment object with the given sequences
204 * sequences as an array
206 public static void setOrder(AlignmentI align, SequenceI[] seqs)
208 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
209 List<SequenceI> algn = align.getSequences();
212 List<SequenceI> tmp = new ArrayList<>();
214 for (int i = 0; i < seqs.length; i++)
216 if (algn.contains(seqs[i]))
223 // User may have hidden seqs, then clicked undo or redo
224 for (int i = 0; i < tmp.size(); i++)
226 algn.add(tmp.get(i));
232 * Sorts by ID. Numbers are sorted before letters.
235 * The alignment object to sort
237 public static void sortByID(AlignmentI align)
239 int nSeq = align.getHeight();
241 String[] ids = new String[nSeq];
242 SequenceI[] seqs = new SequenceI[nSeq];
244 for (int i = 0; i < nSeq; i++)
246 ids[i] = align.getSequenceAt(i).getName();
247 seqs[i] = align.getSequenceAt(i);
250 QuickSort.sort(ids, seqs);
252 AlignmentSorter as = getInstance();
253 if (as.sortIdAscending)
255 setReverseOrder(align, seqs);
259 setOrder(align, seqs);
262 as.sortIdAscending = !as.sortIdAscending;
266 * Sorts by sequence length
269 * The alignment object to sort
271 public static void sortByLength(AlignmentI align)
273 int nSeq = align.getHeight();
275 float[] length = new float[nSeq];
276 SequenceI[] seqs = new SequenceI[nSeq];
278 for (int i = 0; i < nSeq; i++)
280 seqs[i] = align.getSequenceAt(i);
281 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
284 QuickSort.sort(length, seqs);
286 AlignmentSorter as = getInstance();
288 if (as.sortLengthAscending)
290 setReverseOrder(align, seqs);
294 setOrder(align, seqs);
297 as.sortLengthAscending = !as.sortLengthAscending;
301 * Sorts the alignment by size of group. <br>
302 * Maintains the order of sequences in each group by order in given alignment
306 * sorts the given alignment object by group
308 public static void sortByGroup(AlignmentI align)
310 // MAINTAINS ORIGNAL SEQUENCE ORDER,
311 // ORDERS BY GROUP SIZE
312 List<SequenceGroup> groups = new ArrayList<>();
314 AlignmentSorter as = getInstance();
316 if (groups.hashCode() != as.lastGroupHash)
318 as.sortGroupAscending = true;
319 as.lastGroupHash = groups.hashCode();
323 as.sortGroupAscending = !as.sortGroupAscending;
326 // SORTS GROUPS BY SIZE
327 // ////////////////////
328 for (SequenceGroup sg : align.getGroups())
330 for (int j = 0; j < groups.size(); j++)
332 SequenceGroup sg2 = groups.get(j);
334 if (sg.getSize() > sg2.getSize())
342 if (!groups.contains(sg))
348 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
349 // /////////////////////////////////////////////
350 List<SequenceI> seqs = new ArrayList<>();
352 for (int i = 0; i < groups.size(); i++)
354 SequenceGroup sg = groups.get(i);
355 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
357 for (int j = 0; j < orderedseqs.length; j++)
359 seqs.add(orderedseqs[j]);
363 if (as.sortGroupAscending)
365 setOrder(align, seqs);
369 setReverseOrder(align,
370 vectorSubsetToArray(seqs, align.getSequences()));
375 * Select sequences in order from tmp that is present in mask, and any
376 * remaining sequences in mask not in tmp
379 * thread safe collection of sequences
381 * thread safe collection of sequences
383 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
385 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
386 List<SequenceI> mask)
389 // tmp2 = tmp.retainAll(mask);
390 // return tmp2.addAll(mask.removeAll(tmp2))
392 ArrayList<SequenceI> seqs = new ArrayList<>();
394 boolean[] tmask = new boolean[mask.size()];
396 for (i = 0; i < mask.size(); i++)
401 for (i = 0; i < tmp.size(); i++)
403 SequenceI sq = tmp.get(i);
404 idx = mask.indexOf(sq);
405 if (idx > -1 && tmask[idx])
412 for (i = 0; i < tmask.length; i++)
416 seqs.add(mask.get(i));
420 return seqs.toArray(new SequenceI[seqs.size()]);
424 * Sorts by a given AlignmentOrder object
429 * specified order for alignment
431 public static void sortBy(AlignmentI align, AlignmentOrder order)
433 // Get an ordered vector of sequences which may also be present in align
434 List<SequenceI> tmp = order.getOrder();
436 AlignmentSorter as = getInstance();
438 if (as.lastOrder == order)
440 as.sortOrderAscending = !as.sortOrderAscending;
444 as.sortOrderAscending = true;
447 if (as.sortOrderAscending)
449 setOrder(align, tmp);
453 setReverseOrder(align,
454 vectorSubsetToArray(tmp, align.getSequences()));
466 * @return DOCUMENT ME!
468 private static List<SequenceI> getOrderByTree(AlignmentI align,
471 int nSeq = align.getHeight();
473 List<SequenceI> tmp = new ArrayList<>();
475 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
477 if (tmp.size() != nSeq)
479 // TODO: JBPNote - decide if this is always an error
480 // (eg. not when a tree is associated to another alignment which has more
482 if (tmp.size() != nSeq)
484 addStrays(align, tmp);
487 if (tmp.size() != nSeq)
489 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
491 + " in getOrderByTree - tree contains sequences not in alignment");
499 * Sorts the alignment by a given tree
506 public static void sortByTree(AlignmentI align, TreeModel tree)
508 List<SequenceI> tmp = getOrderByTree(align, tree);
510 AlignmentSorter as = getInstance();
512 // tmp should properly permute align with tree.
513 if (as.lastTree != tree)
515 as.sortTreeAscending = true;
520 as.sortTreeAscending = !as.sortTreeAscending;
523 if (as.sortTreeAscending)
525 setOrder(align, tmp);
529 setReverseOrder(align,
530 vectorSubsetToArray(tmp, align.getSequences()));
542 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
544 int nSeq = align.getHeight();
546 for (int i = 0; i < nSeq; i++)
548 if (!tmp.contains(align.getSequenceAt(i)))
550 tmp.add(align.getSequenceAt(i));
554 if (nSeq != tmp.size())
557 .println("ERROR: Size still not right even after addStrays");
571 * @return DOCUMENT ME!
573 private static List<SequenceI> _sortByTree(SequenceNode node,
574 List<SequenceI> tmp, List<SequenceI> seqset)
581 SequenceNode left = (SequenceNode) node.left();
582 SequenceNode right = (SequenceNode) node.right();
584 if ((left == null) && (right == null))
586 if (!node.isPlaceholder() && (node.element() != null))
588 if (node.element() instanceof SequenceI)
590 if (!tmp.contains(node.element())) // && (seqset==null ||
591 // seqset.size()==0 ||
592 // seqset.contains(tmp)))
594 tmp.add((SequenceI) node.element());
603 _sortByTree(left, tmp, seqset);
604 _sortByTree(right, tmp, seqset);
611 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
616 * recover the order of sequences given by the safe numbering scheme introducd
617 * SeqsetUtils.uniquify.
619 public static void recoverOrder(SequenceI[] alignment)
621 float[] ids = new float[alignment.length];
623 for (int i = 0; i < alignment.length; i++)
625 ids[i] = (new Float(alignment[i].getName().substring(8)))
629 jalview.util.QuickSort.sort(ids, alignment);
633 * Sort sequence in order of increasing score attribute for annotation with a
634 * particular scoreLabel. Or reverse if same label was used previously
637 * exact label for sequence associated AlignmentAnnotation scores to
640 * sequences to be sorted
642 public static void sortByAnnotationScore(String scoreLabel,
643 AlignmentI alignment)
645 SequenceI[] seqs = alignment.getSequencesArray();
646 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
648 int hasScores = 0; // number of scores present on set
649 double[] scores = new double[seqs.length];
650 double min = 0, max = 0;
651 for (int i = 0; i < seqs.length; i++)
653 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
654 if (scoreAnn != null)
658 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
662 max = min = scores[i];
683 return; // do nothing - no scores present to sort by.
685 if (hasScores < seqs.length)
687 for (int i = 0; i < seqs.length; i++)
691 scores[i] = (max + i + 1.0);
696 jalview.util.QuickSort.sort(scores, seqs);
698 AlignmentSorter as = getInstance();
700 if (as.lastSortByAnnotation != scoreLabel)
702 as.lastSortByAnnotation = scoreLabel;
703 setOrder(alignment, seqs);
707 setReverseOrder(alignment, seqs);
712 * Sort sequences by feature score or density, optionally restricted by
713 * feature types, feature groups, or alignment start/end positions.
715 * If the sort is repeated for the same combination of types and groups, sort
718 * @param featureTypes
719 * a list of feature types to include (or null for all)
721 * a list of feature groups to include (or null for all)
723 * start column position to include (base zero)
725 * end column position to include (base zero)
727 * the alignment to be sorted
729 * either "average_score" or "density" ("text" not yet implemented)
731 public static void sortByFeature(List<String> featureTypes,
732 List<String> groups, final int startCol, final int endCol,
733 AlignmentI alignment, String method)
735 if (method != FEATURE_SCORE && method != FEATURE_LABEL
736 && method != FEATURE_DENSITY)
739 .format("Implementation Error - sortByFeature method must be either '%s' or '%s'",
740 FEATURE_SCORE, FEATURE_DENSITY);
741 System.err.println(msg);
745 flipFeatureSortIfUnchanged(method, featureTypes, groups, startCol, endCol);
747 SequenceI[] seqs = alignment.getSequencesArray();
749 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
751 int hasScores = 0; // number of scores present on set
752 double[] scores = new double[seqs.length];
753 int[] seqScores = new int[seqs.length];
754 Object[][] feats = new Object[seqs.length][];
758 for (int i = 0; i < seqs.length; i++)
761 * get sequence residues overlapping column region
762 * and features for residue positions and specified types
764 String[] types = featureTypes == null ? null : featureTypes
765 .toArray(new String[featureTypes.size()]);
766 List<SequenceFeature> sfs = seqs[i].findFeatures(startCol + 1,
772 Iterator<SequenceFeature> it = sfs.listIterator();
775 SequenceFeature sf = it.next();
778 * accept all features with null or empty group, otherwise
779 * check group is one of the currently visible groups
781 String featureGroup = sf.getFeatureGroup();
782 if (groups != null && featureGroup != null
783 && !"".equals(featureGroup)
784 && !groups.contains(featureGroup))
790 float score = sf.getScore();
791 if (FEATURE_SCORE.equals(method) && !Float.isNaN(score))
793 if (seqScores[i] == 0)
800 // take the first instance of this score // ??
805 feats[i] = sfs.toArray(new SequenceFeature[sfs.size()]);
808 if (method == FEATURE_LABEL)
810 // order the labels by alphabet (not yet implemented)
811 String[] labs = new String[sfs.size()];
812 for (int l = 0; l < sfs.size(); l++)
814 SequenceFeature sf = sfs.get(l);
815 String description = sf.getDescription();
816 labs[l] = (description != null ? description : sf.getType());
818 QuickSort.sort(labs, feats[i]);
823 // compute average score
824 scores[i] /= seqScores[i];
825 // update the score bounds.
833 max = Math.max(max, scores[i]);
834 min = Math.min(min, scores[i]);
839 boolean doSort = false;
841 if (FEATURE_SCORE.equals(method))
845 return; // do nothing - no scores present to sort by.
848 if (hasScores < seqs.length)
850 for (int i = 0; i < seqs.length; i++)
854 scores[i] = (max + 1 + i);
858 // int nf = (feats[i] == null) ? 0
859 // : ((SequenceFeature[]) feats[i]).length;
860 // // System.err.println("Sorting on Score: seq " +
862 // + " Feats: " + nf + " Score : " + scores[i]);
868 else if (FEATURE_DENSITY.equals(method))
870 for (int i = 0; i < seqs.length; i++)
872 int featureCount = feats[i] == null ? 0
873 : ((SequenceFeature[]) feats[i]).length;
874 scores[i] = featureCount;
875 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
876 // " Feats: "+featureCount+" Score : "+scores[i]);
882 QuickSort.sortByDouble(scores, seqs, getInstance().sortByFeatureAscending);
884 setOrder(alignment, seqs);
888 * Builds a string hash of criteria for sorting, and if unchanged from last
889 * time, reverse the sort order
892 * @param featureTypes
897 protected static void flipFeatureSortIfUnchanged(String method,
898 List<String> featureTypes, List<String> groups,
899 final int startCol, final int endCol)
901 StringBuilder sb = new StringBuilder(64);
902 sb.append(startCol).append(method).append(endCol);
903 if (featureTypes != null)
905 Collections.sort(featureTypes);
906 sb.append(featureTypes.toString());
910 Collections.sort(groups);
911 sb.append(groups.toString());
913 String scoreCriteria = sb.toString();
916 * if resorting on the same criteria, toggle sort order
918 AlignmentSorter as = getInstance();
919 if (as.sortByFeatureCriteria == null
920 || !scoreCriteria.equals(as.sortByFeatureCriteria))
922 as.sortByFeatureAscending = true;
926 as.sortByFeatureAscending = !as.sortByFeatureAscending;
928 as.sortByFeatureCriteria = scoreCriteria;