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.Instance;
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
58 private AlignmentSorter()
63 private static AlignmentSorter getInstance()
65 Instance j = Instance.getInstance();
66 return (j.alignmentSorter == null
67 ? j.alignmentSorter = new AlignmentSorter()
72 * types of feature ordering: Sort by score : average score - or total score -
73 * over all features in region Sort by feature label text: (or if null -
74 * feature type text) - numerical or alphabetical Sort by feature density:
75 * based on counts - ignoring individual text or scores for each feature
77 public static final String FEATURE_SCORE = "average_score";
79 public static final String FEATURE_LABEL = "text";
81 public static final String FEATURE_DENSITY = "density";
84 * todo: refactor searches to follow a basic pattern: (search property, last
85 * search state, current sort direction)
87 boolean sortIdAscending = true;
89 int lastGroupHash = 0;
91 boolean sortGroupAscending = true;
93 AlignmentOrder lastOrder = null;
95 boolean sortOrderAscending = true;
97 TreeModel lastTree = null;
99 boolean sortTreeAscending = true;
103 * last Annotation Label used for sort by Annotation score
105 private String lastSortByAnnotation;
108 * string hash of last arguments to sortByFeature (sort order toggles if this
109 * is unchanged between sorts)
111 private String sortByFeatureCriteria;
113 private boolean sortByFeatureAscending = true;
115 private boolean sortLengthAscending;
118 * Sorts sequences in the alignment by Percentage Identity with the given
119 * reference sequence, sorting the highest identity to the top
127 public static void sortByPID(AlignmentI align, SequenceI s)
129 int nSeq = align.getHeight();
131 float[] scores = new float[nSeq];
132 SequenceI[] seqs = new SequenceI[nSeq];
133 String refSeq = s.getSequenceAsString();
135 SimilarityParams pidParams = new SimilarityParams(true, true, true,
137 for (int i = 0; i < nSeq; i++)
139 scores[i] = (float) PIDModel.computePID(
140 align.getSequenceAt(i).getSequenceAsString(), refSeq,
142 seqs[i] = align.getSequenceAt(i);
145 QuickSort.sort(scores, seqs);
147 setReverseOrder(align, seqs);
151 * Reverse the order of the sort
158 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
160 int nSeq = seqs.length;
170 len = (nSeq + 1) / 2;
173 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
174 List<SequenceI> asq = align.getSequences();
177 for (int i = 0; i < len; i++)
179 // SequenceI tmp = seqs[i];
180 asq.set(i, seqs[nSeq - i - 1]);
181 asq.set(nSeq - i - 1, seqs[i]);
187 * Sets the Alignment object with the given sequences
190 * Alignment object to be updated
192 * sequences as a vector
194 private static void setOrder(AlignmentI align, List<SequenceI> tmp)
196 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
200 * Sets the Alignment object with the given sequences
205 * sequences as an array
207 public static void setOrder(AlignmentI align, SequenceI[] seqs)
209 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
210 List<SequenceI> algn = align.getSequences();
213 List<SequenceI> tmp = new ArrayList<>();
215 for (int i = 0; i < seqs.length; i++)
217 if (algn.contains(seqs[i]))
224 // User may have hidden seqs, then clicked undo or redo
225 for (int i = 0; i < tmp.size(); i++)
227 algn.add(tmp.get(i));
233 * Sorts by ID. Numbers are sorted before letters.
236 * The alignment object to sort
238 public static void sortByID(AlignmentI align)
240 int nSeq = align.getHeight();
242 String[] ids = new String[nSeq];
243 SequenceI[] seqs = new SequenceI[nSeq];
245 for (int i = 0; i < nSeq; i++)
247 ids[i] = align.getSequenceAt(i).getName();
248 seqs[i] = align.getSequenceAt(i);
251 QuickSort.sort(ids, seqs);
253 AlignmentSorter as = getInstance();
254 if (as.sortIdAscending)
256 setReverseOrder(align, seqs);
260 setOrder(align, seqs);
263 as.sortIdAscending = !as.sortIdAscending;
267 * Sorts by sequence length
270 * The alignment object to sort
272 public static void sortByLength(AlignmentI align)
274 int nSeq = align.getHeight();
276 float[] length = new float[nSeq];
277 SequenceI[] seqs = new SequenceI[nSeq];
279 for (int i = 0; i < nSeq; i++)
281 seqs[i] = align.getSequenceAt(i);
282 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
285 QuickSort.sort(length, seqs);
287 AlignmentSorter as = getInstance();
289 if (as.sortLengthAscending)
291 setReverseOrder(align, seqs);
295 setOrder(align, seqs);
298 as.sortLengthAscending = !as.sortLengthAscending;
302 * Sorts the alignment by size of group. <br>
303 * Maintains the order of sequences in each group by order in given alignment
307 * sorts the given alignment object by group
309 public static void sortByGroup(AlignmentI align)
311 // MAINTAINS ORIGNAL SEQUENCE ORDER,
312 // ORDERS BY GROUP SIZE
313 List<SequenceGroup> groups = new ArrayList<>();
315 AlignmentSorter as = getInstance();
317 if (groups.hashCode() != as.lastGroupHash)
319 as.sortGroupAscending = true;
320 as.lastGroupHash = groups.hashCode();
324 as.sortGroupAscending = !as.sortGroupAscending;
327 // SORTS GROUPS BY SIZE
328 // ////////////////////
329 for (SequenceGroup sg : align.getGroups())
331 for (int j = 0; j < groups.size(); j++)
333 SequenceGroup sg2 = groups.get(j);
335 if (sg.getSize() > sg2.getSize())
343 if (!groups.contains(sg))
349 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
350 // /////////////////////////////////////////////
351 List<SequenceI> seqs = new ArrayList<>();
353 for (int i = 0; i < groups.size(); i++)
355 SequenceGroup sg = groups.get(i);
356 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
358 for (int j = 0; j < orderedseqs.length; j++)
360 seqs.add(orderedseqs[j]);
364 if (as.sortGroupAscending)
366 setOrder(align, seqs);
370 setReverseOrder(align,
371 vectorSubsetToArray(seqs, align.getSequences()));
376 * Select sequences in order from tmp that is present in mask, and any
377 * remaining sequences in mask not in tmp
380 * thread safe collection of sequences
382 * thread safe collection of sequences
384 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
386 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
387 List<SequenceI> mask)
390 // tmp2 = tmp.retainAll(mask);
391 // return tmp2.addAll(mask.removeAll(tmp2))
393 ArrayList<SequenceI> seqs = new ArrayList<>();
395 boolean[] tmask = new boolean[mask.size()];
397 for (i = 0; i < mask.size(); i++)
402 for (i = 0; i < tmp.size(); i++)
404 SequenceI sq = tmp.get(i);
405 idx = mask.indexOf(sq);
406 if (idx > -1 && tmask[idx])
413 for (i = 0; i < tmask.length; i++)
417 seqs.add(mask.get(i));
421 return seqs.toArray(new SequenceI[seqs.size()]);
425 * Sorts by a given AlignmentOrder object
430 * specified order for alignment
432 public static void sortBy(AlignmentI align, AlignmentOrder order)
434 // Get an ordered vector of sequences which may also be present in align
435 List<SequenceI> tmp = order.getOrder();
437 AlignmentSorter as = getInstance();
439 if (as.lastOrder == order)
441 as.sortOrderAscending = !as.sortOrderAscending;
445 as.sortOrderAscending = true;
448 if (as.sortOrderAscending)
450 setOrder(align, tmp);
454 setReverseOrder(align,
455 vectorSubsetToArray(tmp, align.getSequences()));
467 * @return DOCUMENT ME!
469 private static List<SequenceI> getOrderByTree(AlignmentI align,
472 int nSeq = align.getHeight();
474 List<SequenceI> tmp = new ArrayList<>();
476 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
478 if (tmp.size() != nSeq)
480 // TODO: JBPNote - decide if this is always an error
481 // (eg. not when a tree is associated to another alignment which has more
483 if (tmp.size() != nSeq)
485 addStrays(align, tmp);
488 if (tmp.size() != nSeq)
490 System.err.println("WARNING: tmp.size()=" + tmp.size() + " != nseq="
492 + " in getOrderByTree - tree contains sequences not in alignment");
500 * Sorts the alignment by a given tree
507 public static void sortByTree(AlignmentI align, TreeModel tree)
509 List<SequenceI> tmp = getOrderByTree(align, tree);
511 AlignmentSorter as = getInstance();
513 // tmp should properly permute align with tree.
514 if (as.lastTree != tree)
516 as.sortTreeAscending = true;
521 as.sortTreeAscending = !as.sortTreeAscending;
524 if (as.sortTreeAscending)
526 setOrder(align, tmp);
530 setReverseOrder(align,
531 vectorSubsetToArray(tmp, align.getSequences()));
543 private static void addStrays(AlignmentI align, List<SequenceI> tmp)
545 int nSeq = align.getHeight();
547 for (int i = 0; i < nSeq; i++)
549 if (!tmp.contains(align.getSequenceAt(i)))
551 tmp.add(align.getSequenceAt(i));
555 if (nSeq != tmp.size())
558 .println("ERROR: Size still not right even after addStrays");
572 * @return DOCUMENT ME!
574 private static List<SequenceI> _sortByTree(SequenceNode node,
575 List<SequenceI> tmp, List<SequenceI> seqset)
582 SequenceNode left = (SequenceNode) node.left();
583 SequenceNode right = (SequenceNode) node.right();
585 if ((left == null) && (right == null))
587 if (!node.isPlaceholder() && (node.element() != null))
589 if (node.element() instanceof SequenceI)
591 if (!tmp.contains(node.element())) // && (seqset==null ||
592 // seqset.size()==0 ||
593 // seqset.contains(tmp)))
595 tmp.add((SequenceI) node.element());
604 _sortByTree(left, tmp, seqset);
605 _sortByTree(right, tmp, seqset);
612 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
617 * recover the order of sequences given by the safe numbering scheme introducd
618 * SeqsetUtils.uniquify.
620 public static void recoverOrder(SequenceI[] alignment)
622 float[] ids = new float[alignment.length];
624 for (int i = 0; i < alignment.length; i++)
626 ids[i] = (new Float(alignment[i].getName().substring(8)))
630 jalview.util.QuickSort.sort(ids, alignment);
634 * Sort sequence in order of increasing score attribute for annotation with a
635 * particular scoreLabel. Or reverse if same label was used previously
638 * exact label for sequence associated AlignmentAnnotation scores to
641 * sequences to be sorted
643 public static void sortByAnnotationScore(String scoreLabel,
644 AlignmentI alignment)
646 SequenceI[] seqs = alignment.getSequencesArray();
647 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
649 int hasScores = 0; // number of scores present on set
650 double[] scores = new double[seqs.length];
651 double min = 0, max = 0;
652 for (int i = 0; i < seqs.length; i++)
654 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
655 if (scoreAnn != null)
659 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
663 max = min = scores[i];
684 return; // do nothing - no scores present to sort by.
686 if (hasScores < seqs.length)
688 for (int i = 0; i < seqs.length; i++)
692 scores[i] = (max + i + 1.0);
697 jalview.util.QuickSort.sort(scores, seqs);
699 AlignmentSorter as = getInstance();
701 if (as.lastSortByAnnotation != scoreLabel)
703 as.lastSortByAnnotation = scoreLabel;
704 setOrder(alignment, seqs);
708 setReverseOrder(alignment, seqs);
713 * Sort sequences by feature score or density, optionally restricted by
714 * feature types, feature groups, or alignment start/end positions.
716 * If the sort is repeated for the same combination of types and groups, sort
719 * @param featureTypes
720 * a list of feature types to include (or null for all)
722 * a list of feature groups to include (or null for all)
724 * start column position to include (base zero)
726 * end column position to include (base zero)
728 * the alignment to be sorted
730 * either "average_score" or "density" ("text" not yet implemented)
732 public static void sortByFeature(List<String> featureTypes,
733 List<String> groups, final int startCol, final int endCol,
734 AlignmentI alignment, String method)
736 if (method != FEATURE_SCORE && method != FEATURE_LABEL
737 && method != FEATURE_DENSITY)
740 .format("Implementation Error - sortByFeature method must be either '%s' or '%s'",
741 FEATURE_SCORE, FEATURE_DENSITY);
742 System.err.println(msg);
746 flipFeatureSortIfUnchanged(method, featureTypes, groups, startCol, endCol);
748 SequenceI[] seqs = alignment.getSequencesArray();
750 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
752 int hasScores = 0; // number of scores present on set
753 double[] scores = new double[seqs.length];
754 int[] seqScores = new int[seqs.length];
755 Object[][] feats = new Object[seqs.length][];
759 for (int i = 0; i < seqs.length; i++)
762 * get sequence residues overlapping column region
763 * and features for residue positions and specified types
765 String[] types = featureTypes == null ? null : featureTypes
766 .toArray(new String[featureTypes.size()]);
767 List<SequenceFeature> sfs = seqs[i].findFeatures(startCol + 1,
773 Iterator<SequenceFeature> it = sfs.listIterator();
776 SequenceFeature sf = it.next();
779 * accept all features with null or empty group, otherwise
780 * check group is one of the currently visible groups
782 String featureGroup = sf.getFeatureGroup();
783 if (groups != null && featureGroup != null
784 && !"".equals(featureGroup)
785 && !groups.contains(featureGroup))
791 float score = sf.getScore();
792 if (FEATURE_SCORE.equals(method) && !Float.isNaN(score))
794 if (seqScores[i] == 0)
801 // take the first instance of this score // ??
806 feats[i] = sfs.toArray(new SequenceFeature[sfs.size()]);
809 if (method == FEATURE_LABEL)
811 // order the labels by alphabet (not yet implemented)
812 String[] labs = new String[sfs.size()];
813 for (int l = 0; l < sfs.size(); l++)
815 SequenceFeature sf = sfs.get(l);
816 String description = sf.getDescription();
817 labs[l] = (description != null ? description : sf.getType());
819 QuickSort.sort(labs, feats[i]);
824 // compute average score
825 scores[i] /= seqScores[i];
826 // update the score bounds.
834 max = Math.max(max, scores[i]);
835 min = Math.min(min, scores[i]);
840 boolean doSort = false;
842 if (FEATURE_SCORE.equals(method))
846 return; // do nothing - no scores present to sort by.
849 if (hasScores < seqs.length)
851 for (int i = 0; i < seqs.length; i++)
855 scores[i] = (max + 1 + i);
859 // int nf = (feats[i] == null) ? 0
860 // : ((SequenceFeature[]) feats[i]).length;
861 // // System.err.println("Sorting on Score: seq " +
863 // + " Feats: " + nf + " Score : " + scores[i]);
869 else if (FEATURE_DENSITY.equals(method))
871 for (int i = 0; i < seqs.length; i++)
873 int featureCount = feats[i] == null ? 0
874 : ((SequenceFeature[]) feats[i]).length;
875 scores[i] = featureCount;
876 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
877 // " Feats: "+featureCount+" Score : "+scores[i]);
883 QuickSort.sortByDouble(scores, seqs, getInstance().sortByFeatureAscending);
885 setOrder(alignment, seqs);
889 * Builds a string hash of criteria for sorting, and if unchanged from last
890 * time, reverse the sort order
893 * @param featureTypes
898 protected static void flipFeatureSortIfUnchanged(String method,
899 List<String> featureTypes, List<String> groups,
900 final int startCol, final int endCol)
902 StringBuilder sb = new StringBuilder(64);
903 sb.append(startCol).append(method).append(endCol);
904 if (featureTypes != null)
906 Collections.sort(featureTypes);
907 sb.append(featureTypes.toString());
911 Collections.sort(groups);
912 sb.append(groups.toString());
914 String scoreCriteria = sb.toString();
917 * if resorting on the same criteria, toggle sort order
919 AlignmentSorter as = getInstance();
920 if (as.sortByFeatureCriteria == null
921 || !scoreCriteria.equals(as.sortByFeatureCriteria))
923 as.sortByFeatureAscending = true;
927 as.sortByFeatureAscending = !as.sortByFeatureAscending;
929 as.sortByFeatureCriteria = scoreCriteria;