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.Jalview;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentOrder;
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
59 * types of feature ordering: Sort by score : average score - or total score -
60 * over all features in region Sort by feature label text: (or if null -
61 * feature type text) - numerical or alphabetical Sort by feature density:
62 * based on counts - ignoring individual text or scores for each feature
64 public static final String FEATURE_SCORE = "average_score";
66 public static final String FEATURE_LABEL = "text";
68 public static final String FEATURE_DENSITY = "density";
70 public static AlignmentSorter getInstance()
72 Jalview j = Jalview.getInstance();
73 return (j.alignmentSorter == null
74 ? j.alignmentSorter = new AlignmentSorter()
79 * todo: refactor searches to follow a basic pattern: (search property, last
80 * search state, current sort direction)
82 boolean sortIdAscending = true;
84 int lastGroupHash = 0;
86 boolean sortGroupAscending = true;
88 AlignmentOrder lastOrder = null;
90 boolean sortOrderAscending = true;
92 TreeModel lastTree = null;
94 boolean sortTreeAscending = true;
98 * last Annotation Label used for sort by Annotation score
100 private String lastSortByAnnotation;
103 * string hash of last arguments to sortByFeature (sort order toggles if this
104 * is unchanged between sorts)
106 private String sortByFeatureCriteria;
108 private boolean sortByFeatureAscending = true;
110 private boolean sortLengthAscending;
113 * Sorts sequences in the alignment by Percentage Identity with the given
114 * reference sequence, sorting the highest identity to the top
122 public static void sortByPID(AlignmentI align, SequenceI s)
124 int nSeq = align.getHeight();
126 float[] scores = new float[nSeq];
127 SequenceI[] seqs = new SequenceI[nSeq];
128 String refSeq = s.getSequenceAsString();
130 SimilarityParams pidParams = new SimilarityParams(true, true, true,
132 for (int i = 0; i < nSeq; i++)
134 scores[i] = (float) PIDModel.computePID(
135 align.getSequenceAt(i).getSequenceAsString(), refSeq,
137 seqs[i] = align.getSequenceAt(i);
140 QuickSort.sort(scores, seqs);
142 setReverseOrder(align, seqs);
146 * Reverse the order of the sort
153 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
155 int nSeq = seqs.length;
165 len = (nSeq + 1) / 2;
168 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
169 List<SequenceI> asq = align.getSequences();
172 for (int i = 0; i < len; i++)
174 // SequenceI tmp = seqs[i];
175 asq.set(i, seqs[nSeq - i - 1]);
176 asq.set(nSeq - i - 1, seqs[i]);
182 * Sets the Alignment object with the given sequences
185 * Alignment object to be updated
187 * sequences as a vector
189 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
191 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
195 * Sets the Alignment object with the given sequences
200 * sequences as an array
202 public static void setOrder(AlignmentI align, SequenceI[] seqs)
204 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
205 List<SequenceI> algn = align.getSequences();
208 List<SequenceI> tmp = new ArrayList<>();
210 for (int i = 0; i < seqs.length; i++)
212 if (algn.contains(seqs[i]))
219 // User may have hidden seqs, then clicked undo or redo
220 for (int i = 0; i < tmp.size(); i++)
222 algn.add(tmp.get(i));
228 * Sorts by ID. Numbers are sorted before letters.
231 * The alignment object to sort
233 public static void sortByID(AlignmentI align)
235 int nSeq = align.getHeight();
237 String[] ids = new String[nSeq];
238 SequenceI[] seqs = new SequenceI[nSeq];
240 for (int i = 0; i < nSeq; i++)
242 ids[i] = align.getSequenceAt(i).getName();
243 seqs[i] = align.getSequenceAt(i);
246 QuickSort.sort(ids, seqs);
248 AlignmentSorter as = getInstance();
249 if (as.sortIdAscending)
251 setReverseOrder(align, seqs);
255 setOrder(align, seqs);
258 as.sortIdAscending = !as.sortIdAscending;
262 * Sorts by sequence length
265 * The alignment object to sort
267 public static void sortByLength(AlignmentI align)
269 int nSeq = align.getHeight();
271 float[] length = new float[nSeq];
272 SequenceI[] seqs = new SequenceI[nSeq];
274 for (int i = 0; i < nSeq; i++)
276 seqs[i] = align.getSequenceAt(i);
277 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
280 QuickSort.sort(length, seqs);
282 AlignmentSorter as = getInstance();
284 if (as.sortLengthAscending)
286 setReverseOrder(align, seqs);
290 setOrder(align, seqs);
293 as.sortLengthAscending = !as.sortLengthAscending;
297 * Sorts the alignment by size of group. <br>
298 * Maintains the order of sequences in each group by order in given alignment
302 * sorts the given alignment object by group
304 public static void sortByGroup(AlignmentI align)
306 // MAINTAINS ORIGNAL SEQUENCE ORDER,
307 // ORDERS BY GROUP SIZE
308 List<SequenceGroup> groups = new ArrayList<>();
310 AlignmentSorter as = getInstance();
312 if (groups.hashCode() != as.lastGroupHash)
314 as.sortGroupAscending = true;
315 as.lastGroupHash = groups.hashCode();
319 as.sortGroupAscending = !as.sortGroupAscending;
322 // SORTS GROUPS BY SIZE
323 // ////////////////////
324 for (SequenceGroup sg : align.getGroups())
326 for (int j = 0; j < groups.size(); j++)
328 SequenceGroup sg2 = groups.get(j);
330 if (sg.getSize() > sg2.getSize())
338 if (!groups.contains(sg))
344 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
345 // /////////////////////////////////////////////
346 List<SequenceI> seqs = new ArrayList<>();
348 for (int i = 0; i < groups.size(); i++)
350 SequenceGroup sg = groups.get(i);
351 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
353 for (int j = 0; j < orderedseqs.length; j++)
355 seqs.add(orderedseqs[j]);
359 if (as.sortGroupAscending)
361 setOrder(align, seqs);
365 setReverseOrder(align,
366 vectorSubsetToArray(seqs, align.getSequences()));
371 * Select sequences in order from tmp that is present in mask, and any
372 * remaining sequences in mask not in tmp
375 * thread safe collection of sequences
377 * thread safe collection of sequences
379 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
381 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
382 List<SequenceI> mask)
385 // tmp2 = tmp.retainAll(mask);
386 // return tmp2.addAll(mask.removeAll(tmp2))
388 ArrayList<SequenceI> seqs = new ArrayList<>();
390 boolean[] tmask = new boolean[mask.size()];
392 for (i = 0; i < mask.size(); i++)
397 for (i = 0; i < tmp.size(); i++)
399 SequenceI sq = tmp.get(i);
400 idx = mask.indexOf(sq);
401 if (idx > -1 && tmask[idx])
408 for (i = 0; i < tmask.length; i++)
412 seqs.add(mask.get(i));
416 return seqs.toArray(new SequenceI[seqs.size()]);
420 * Sorts by a given AlignmentOrder object
425 * specified order for alignment
427 public static void sortBy(AlignmentI align, AlignmentOrder order)
429 // Get an ordered vector of sequences which may also be present in align
430 List<SequenceI> tmp = order.getOrder();
432 AlignmentSorter as = getInstance();
434 if (as.lastOrder == order)
436 as.sortOrderAscending = !as.sortOrderAscending;
440 as.sortOrderAscending = true;
443 if (as.sortOrderAscending)
445 setOrder(align, tmp);
449 setReverseOrder(align,
450 vectorSubsetToArray(tmp, align.getSequences()));
462 * @return DOCUMENT ME!
464 private static List<SequenceI> getOrderByTree(AlignmentI align,
467 int nSeq = align.getHeight();
469 List<SequenceI> tmp = new ArrayList<>();
471 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
473 if (tmp.size() != nSeq)
475 // TODO: JBPNote - decide if this is always an error
476 // (eg. not when a tree is associated to another alignment which has more
478 if (tmp.size() != nSeq)
480 addStrays(align, tmp);
483 if (tmp.size() != nSeq)
485 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
487 + " in getOrderByTree - tree contains sequences not in alignment");
495 * Sorts the alignment by a given tree
502 public static void sortByTree(AlignmentI align, TreeModel tree)
504 List<SequenceI> tmp = getOrderByTree(align, tree);
506 AlignmentSorter as = getInstance();
508 // tmp should properly permute align with tree.
509 if (as.lastTree != tree)
511 as.sortTreeAscending = true;
516 as.sortTreeAscending = !as.sortTreeAscending;
519 if (as.sortTreeAscending)
521 setOrder(align, tmp);
525 setReverseOrder(align,
526 vectorSubsetToArray(tmp, align.getSequences()));
538 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
540 int nSeq = align.getHeight();
542 for (int i = 0; i < nSeq; i++)
544 if (!tmp.contains(align.getSequenceAt(i)))
546 tmp.add(align.getSequenceAt(i));
550 if (nSeq != tmp.size())
553 .println("ERROR: Size still not right even after addStrays");
567 * @return DOCUMENT ME!
569 private static List<SequenceI> _sortByTree(SequenceNode node,
570 List<SequenceI> tmp, List<SequenceI> seqset)
577 SequenceNode left = (SequenceNode) node.left();
578 SequenceNode right = (SequenceNode) node.right();
580 if ((left == null) && (right == null))
582 if (!node.isPlaceholder() && (node.element() != null))
584 if (node.element() instanceof SequenceI)
586 if (!tmp.contains(node.element())) // && (seqset==null ||
587 // seqset.size()==0 ||
588 // seqset.contains(tmp)))
590 tmp.add((SequenceI) node.element());
599 _sortByTree(left, tmp, seqset);
600 _sortByTree(right, tmp, seqset);
607 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
612 * recover the order of sequences given by the safe numbering scheme introducd
613 * SeqsetUtils.uniquify.
615 public static void recoverOrder(SequenceI[] alignment)
617 float[] ids = new float[alignment.length];
619 for (int i = 0; i < alignment.length; i++)
621 ids[i] = (new Float(alignment[i].getName().substring(8)))
625 jalview.util.QuickSort.sort(ids, alignment);
629 * Sort sequence in order of increasing score attribute for annotation with a
630 * particular scoreLabel. Or reverse if same label was used previously
633 * exact label for sequence associated AlignmentAnnotation scores to
636 * sequences to be sorted
638 public static void sortByAnnotationScore(String scoreLabel,
639 AlignmentI alignment)
641 SequenceI[] seqs = alignment.getSequencesArray();
642 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
644 int hasScores = 0; // number of scores present on set
645 double[] scores = new double[seqs.length];
646 double min = 0, max = 0;
647 for (int i = 0; i < seqs.length; i++)
649 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
650 if (scoreAnn != null)
654 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
658 max = min = scores[i];
679 return; // do nothing - no scores present to sort by.
681 if (hasScores < seqs.length)
683 for (int i = 0; i < seqs.length; i++)
687 scores[i] = (max + i + 1.0);
692 jalview.util.QuickSort.sort(scores, seqs);
694 AlignmentSorter as = getInstance();
696 if (as.lastSortByAnnotation != scoreLabel)
698 as.lastSortByAnnotation = scoreLabel;
699 setOrder(alignment, seqs);
703 setReverseOrder(alignment, seqs);
708 * Sort sequences by feature score or density, optionally restricted by
709 * feature types, feature groups, or alignment start/end positions.
711 * If the sort is repeated for the same combination of types and groups, sort
714 * @param featureTypes
715 * a list of feature types to include (or null for all)
717 * a list of feature groups to include (or null for all)
719 * start column position to include (base zero)
721 * end column position to include (base zero)
723 * the alignment to be sorted
725 * either "average_score" or "density" ("text" not yet implemented)
727 public static void sortByFeature(List<String> featureTypes,
728 List<String> groups, final int startCol, final int endCol,
729 AlignmentI alignment, String method)
731 if (method != FEATURE_SCORE && method != FEATURE_LABEL
732 && method != FEATURE_DENSITY)
735 .format("Implementation Error - sortByFeature method must be either '%s' or '%s'",
736 FEATURE_SCORE, FEATURE_DENSITY);
737 System.err.println(msg);
741 flipFeatureSortIfUnchanged(method, featureTypes, groups, startCol, endCol);
743 SequenceI[] seqs = alignment.getSequencesArray();
745 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
747 int hasScores = 0; // number of scores present on set
748 double[] scores = new double[seqs.length];
749 int[] seqScores = new int[seqs.length];
750 Object[][] feats = new Object[seqs.length][];
754 for (int i = 0; i < seqs.length; i++)
757 * get sequence residues overlapping column region
758 * and features for residue positions and specified types
760 String[] types = featureTypes == null ? null : featureTypes
761 .toArray(new String[featureTypes.size()]);
762 List<SequenceFeature> sfs = seqs[i].findFeatures(startCol + 1,
768 Iterator<SequenceFeature> it = sfs.listIterator();
771 SequenceFeature sf = it.next();
774 * accept all features with null or empty group, otherwise
775 * check group is one of the currently visible groups
777 String featureGroup = sf.getFeatureGroup();
778 if (groups != null && featureGroup != null
779 && !"".equals(featureGroup)
780 && !groups.contains(featureGroup))
786 float score = sf.getScore();
787 if (FEATURE_SCORE.equals(method) && !Float.isNaN(score))
789 if (seqScores[i] == 0)
796 // take the first instance of this score // ??
801 feats[i] = sfs.toArray(new SequenceFeature[sfs.size()]);
804 if (method == FEATURE_LABEL)
806 // order the labels by alphabet (not yet implemented)
807 String[] labs = new String[sfs.size()];
808 for (int l = 0; l < sfs.size(); l++)
810 SequenceFeature sf = sfs.get(l);
811 String description = sf.getDescription();
812 labs[l] = (description != null ? description : sf.getType());
814 QuickSort.sort(labs, feats[i]);
819 // compute average score
820 scores[i] /= seqScores[i];
821 // update the score bounds.
829 max = Math.max(max, scores[i]);
830 min = Math.min(min, scores[i]);
835 boolean doSort = false;
837 if (FEATURE_SCORE.equals(method))
841 return; // do nothing - no scores present to sort by.
844 if (hasScores < seqs.length)
846 for (int i = 0; i < seqs.length; i++)
850 scores[i] = (max + 1 + i);
854 // int nf = (feats[i] == null) ? 0
855 // : ((SequenceFeature[]) feats[i]).length;
856 // // System.err.println("Sorting on Score: seq " +
858 // + " Feats: " + nf + " Score : " + scores[i]);
864 else if (FEATURE_DENSITY.equals(method))
866 for (int i = 0; i < seqs.length; i++)
868 int featureCount = feats[i] == null ? 0
869 : ((SequenceFeature[]) feats[i]).length;
870 scores[i] = featureCount;
871 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
872 // " Feats: "+featureCount+" Score : "+scores[i]);
878 QuickSort.sortByDouble(scores, seqs, getInstance().sortByFeatureAscending);
880 setOrder(alignment, seqs);
884 * Builds a string hash of criteria for sorting, and if unchanged from last
885 * time, reverse the sort order
888 * @param featureTypes
893 protected static void flipFeatureSortIfUnchanged(String method,
894 List<String> featureTypes, List<String> groups,
895 final int startCol, final int endCol)
897 StringBuilder sb = new StringBuilder(64);
898 sb.append(startCol).append(method).append(endCol);
899 if (featureTypes != null)
901 Collections.sort(featureTypes);
902 sb.append(featureTypes.toString());
906 Collections.sort(groups);
907 sb.append(groups.toString());
909 String scoreCriteria = sb.toString();
912 * if resorting on the same criteria, toggle sort order
914 AlignmentSorter as = getInstance();
915 if (as.sortByFeatureCriteria == null
916 || !scoreCriteria.equals(as.sortByFeatureCriteria))
918 as.sortByFeatureAscending = true;
922 as.sortByFeatureAscending = !as.sortByFeatureAscending;
924 as.sortByFeatureCriteria = scoreCriteria;