2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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;
25 import jalview.datamodel.*;
26 import jalview.util.*;
29 * Routines for manipulating the order of a multiple sequence alignment TODO:
30 * this class retains some global states concerning sort-order which should be
31 * made attributes for the caller's alignment visualization. TODO: refactor to
32 * allow a subset of selected sequences to be sorted within the context of a
33 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
34 * data mapping to each tobesorted element to use ], Alignment context of
35 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
36 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
37 * resulting from applying the operation to tobesorted should be mapped back to
38 * the original positions in alignment. Otherwise, normal behaviour is to re
39 * order alignment so that tobesorted is sorted and grouped together starting
40 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
41 * becomes a,tb1,tb2,tb3,b,c)
43 public class AlignmentSorter
46 * todo: refactor searches to follow a basic pattern: (search property, last
47 * search state, current sort direction)
49 static boolean sortIdAscending = true;
51 static int lastGroupHash = 0;
53 static boolean sortGroupAscending = true;
55 static AlignmentOrder lastOrder = null;
57 static boolean sortOrderAscending = true;
59 static NJTree lastTree = null;
61 static boolean sortTreeAscending = true;
64 * last Annotation Label used by sortByScore
66 private static String lastSortByScore;
68 private static boolean sortByScoreAscending = true;
71 * compact representation of last arguments to SortByFeatureScore
73 private static String lastSortByFeatureScore;
75 private static boolean sortByFeatureScoreAscending = true;
77 private static boolean sortLengthAscending;
80 * Sort by Percentage Identity w.r.t. s
87 * sequences from align that are to be sorted.
89 public static void sortByPID(AlignmentI align, SequenceI s,
92 sortByPID(align, s, tosort, 0, -1);
96 * Sort by Percentage Identity w.r.t. s
103 * sequences from align that are to be sorted.
105 * start column (0 for beginning
108 public static void sortByPID(AlignmentI align, SequenceI s,
109 SequenceI[] tosort, int start, int end)
111 int nSeq = align.getHeight();
113 float[] scores = new float[nSeq];
114 SequenceI[] seqs = new SequenceI[nSeq];
116 for (int i = 0; i < nSeq; i++)
118 scores[i] = Comparison.PID(align.getSequenceAt(i)
119 .getSequenceAsString(), s.getSequenceAsString());
120 seqs[i] = align.getSequenceAt(i);
123 QuickSort.sort(scores, 0, scores.length - 1, seqs);
125 setReverseOrder(align, seqs);
129 * Reverse the order of the sort
136 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
138 int nSeq = seqs.length;
148 len = (nSeq + 1) / 2;
151 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
153 synchronized (asq = align.getSequences())
155 for (int i = 0; i < len; i++)
157 // SequenceI tmp = seqs[i];
158 asq.set(i, seqs[nSeq - i - 1]);
159 asq.set(nSeq - i - 1, seqs[i]);
165 * Sets the Alignment object with the given sequences
168 * Alignment object to be updated
170 * sequences as a vector
172 private static void setOrder(AlignmentI align, Vector tmp)
174 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
178 * Sets the Alignment object with the given sequences
183 * sequences as an array
185 public static void setOrder(AlignmentI align, SequenceI[] seqs)
187 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
188 List<SequenceI> algn;
189 synchronized (algn = align.getSequences())
191 List<SequenceI> tmp = new ArrayList<SequenceI>();
193 for (int i = 0; i < seqs.length; i++)
195 if (algn.contains(seqs[i]))
202 // User may have hidden seqs, then clicked undo or redo
203 for (int i = 0; i < tmp.size(); i++)
205 algn.add(tmp.get(i));
211 * Sorts by ID. Numbers are sorted before letters.
214 * The alignment object to sort
216 public static void sortByID(AlignmentI align)
218 int nSeq = align.getHeight();
220 String[] ids = new String[nSeq];
221 SequenceI[] seqs = new SequenceI[nSeq];
223 for (int i = 0; i < nSeq; i++)
225 ids[i] = align.getSequenceAt(i).getName();
226 seqs[i] = align.getSequenceAt(i);
229 QuickSort.sort(ids, seqs);
233 setReverseOrder(align, seqs);
237 setOrder(align, seqs);
240 sortIdAscending = !sortIdAscending;
244 * Sorts by sequence length
247 * The alignment object to sort
249 public static void sortByLength(AlignmentI align)
251 int nSeq = align.getHeight();
253 float[] length = new float[nSeq];
254 SequenceI[] seqs = new SequenceI[nSeq];
256 for (int i = 0; i < nSeq; i++)
258 seqs[i] = align.getSequenceAt(i);
259 length[i] = (seqs[i].getEnd() - seqs[i].getStart());
262 QuickSort.sort(length, seqs);
264 if (sortLengthAscending)
266 setReverseOrder(align, seqs);
270 setOrder(align, seqs);
273 sortLengthAscending = !sortLengthAscending;
277 * Sorts the alignment by size of group. <br>
278 * Maintains the order of sequences in each group by order in given alignment
282 * sorts the given alignment object by group
284 public static void sortByGroup(AlignmentI align)
286 // MAINTAINS ORIGNAL SEQUENCE ORDER,
287 // ORDERS BY GROUP SIZE
288 Vector groups = new Vector();
290 if (groups.hashCode() != lastGroupHash)
292 sortGroupAscending = true;
293 lastGroupHash = groups.hashCode();
297 sortGroupAscending = !sortGroupAscending;
300 // SORTS GROUPS BY SIZE
301 // ////////////////////
302 for (SequenceGroup sg : align.getGroups())
304 for (int j = 0; j < groups.size(); j++)
306 SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j);
308 if (sg.getSize() > sg2.getSize())
310 groups.insertElementAt(sg, j);
316 if (!groups.contains(sg))
318 groups.addElement(sg);
322 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
323 // /////////////////////////////////////////////
324 Vector seqs = new Vector();
326 for (int i = 0; i < groups.size(); i++)
328 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
329 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
331 for (int j = 0; j < orderedseqs.length; j++)
333 seqs.addElement(orderedseqs[j]);
337 if (sortGroupAscending)
339 setOrder(align, seqs);
343 setReverseOrder(align,
344 vectorSubsetToArray(seqs, align.getSequences()));
349 * Converts Vector to array. java 1.18 does not have Vector.toArray()
352 * Vector of SequenceI objects
354 * @return array of Sequence[]
356 private static SequenceI[] vectorToArray(Vector tmp)
358 SequenceI[] seqs = new SequenceI[tmp.size()];
360 for (int i = 0; i < tmp.size(); i++)
362 seqs[i] = (SequenceI) tmp.elementAt(i);
369 * Select sequences in order from tmp that is present in mask, and any
370 * remaining seqeunces in mask not in tmp
373 * thread safe collection of sequences
375 * thread safe collection of sequences
377 * @return intersect(tmp,mask)+intersect(complement(tmp),mask)
379 private static SequenceI[] vectorSubsetToArray(List<SequenceI> tmp,
380 List<SequenceI> mask)
382 ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
384 boolean[] tmask = new boolean[mask.size()];
386 for (i = 0; i < mask.size(); i++)
391 for (i = 0; i < tmp.size(); i++)
393 SequenceI sq = tmp.get(i);
394 idx = mask.indexOf(sq);
395 if (idx > -1 && tmask[idx])
402 for (i = 0; i < tmask.length; i++)
406 seqs.add(mask.get(i));
410 return seqs.toArray(new SequenceI[seqs.size()]);
414 * Sorts by a given AlignmentOrder object
419 * specified order for alignment
421 public static void sortBy(AlignmentI align, AlignmentOrder order)
423 // Get an ordered vector of sequences which may also be present in align
424 Vector tmp = order.getOrder();
426 if (lastOrder == order)
428 sortOrderAscending = !sortOrderAscending;
432 sortOrderAscending = true;
435 if (sortOrderAscending)
437 setOrder(align, tmp);
441 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
453 * @return DOCUMENT ME!
455 private static Vector getOrderByTree(AlignmentI align, NJTree tree)
457 int nSeq = align.getHeight();
459 Vector tmp = new Vector();
461 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
463 if (tmp.size() != nSeq)
465 // TODO: JBPNote - decide if this is always an error
466 // (eg. not when a tree is associated to another alignment which has more
468 if (tmp.size() != nSeq)
470 addStrays(align, tmp);
473 if (tmp.size() != nSeq)
476 .println("WARNING: tmp.size()="
480 + " in getOrderByTree - tree contains sequences not in alignment");
488 * Sorts the alignment by a given tree
495 public static void sortByTree(AlignmentI align, NJTree tree)
497 Vector tmp = getOrderByTree(align, tree);
499 // tmp should properly permute align with tree.
500 if (lastTree != tree)
502 sortTreeAscending = true;
507 sortTreeAscending = !sortTreeAscending;
510 if (sortTreeAscending)
512 setOrder(align, tmp);
516 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
528 private static void addStrays(AlignmentI align, Vector seqs)
530 int nSeq = align.getHeight();
532 for (int i = 0; i < nSeq; i++)
534 if (!seqs.contains(align.getSequenceAt(i)))
536 seqs.addElement(align.getSequenceAt(i));
540 if (nSeq != seqs.size())
543 .println("ERROR: Size still not right even after addStrays");
557 * @return DOCUMENT ME!
559 private static Vector _sortByTree(SequenceNode node, Vector tmp,
560 List<SequenceI> seqset)
567 SequenceNode left = (SequenceNode) node.left();
568 SequenceNode right = (SequenceNode) node.right();
570 if ((left == null) && (right == null))
572 if (!node.isPlaceholder() && (node.element() != null))
574 if (node.element() instanceof SequenceI)
576 if (!tmp.contains(node.element())) // && (seqset==null ||
577 // seqset.size()==0 ||
578 // seqset.contains(tmp)))
580 tmp.addElement(node.element());
589 _sortByTree(left, tmp, seqset);
590 _sortByTree(right, tmp, seqset);
597 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
602 * recover the order of sequences given by the safe numbering scheme introducd
603 * SeqsetUtils.uniquify.
605 public static void recoverOrder(SequenceI[] alignment)
607 float[] ids = new float[alignment.length];
609 for (int i = 0; i < alignment.length; i++)
611 ids[i] = (new Float(alignment[i].getName().substring(8)))
615 jalview.util.QuickSort.sort(ids, alignment);
619 * Sort sequence in order of increasing score attribute for annotation with a
620 * particular scoreLabel. Or reverse if same label was used previously
623 * exact label for sequence associated AlignmentAnnotation scores to
626 * sequences to be sorted
628 public static void sortByAnnotationScore(String scoreLabel,
629 AlignmentI alignment)
631 SequenceI[] seqs = alignment.getSequencesArray();
632 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
634 int hasScores = 0; // number of scores present on set
635 double[] scores = new double[seqs.length];
636 double min = 0, max = 0;
637 for (int i = 0; i < seqs.length; i++)
639 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
640 if (scoreAnn != null)
644 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
648 max = min = scores[i];
669 return; // do nothing - no scores present to sort by.
671 if (hasScores < seqs.length)
673 for (int i = 0; i < seqs.length; i++)
677 scores[i] = (max + i + 1.0);
682 jalview.util.QuickSort.sort(scores, seqs);
683 if (lastSortByScore != scoreLabel)
685 lastSortByScore = scoreLabel;
686 setOrder(alignment, seqs);
690 setReverseOrder(alignment, seqs);
695 * types of feature ordering: Sort by score : average score - or total score -
696 * over all features in region Sort by feature label text: (or if null -
697 * feature type text) - numerical or alphabetical Sort by feature density:
698 * based on counts - ignoring individual text or scores for each feature
700 public static String FEATURE_SCORE = "average_score";
702 public static String FEATURE_LABEL = "text";
704 public static String FEATURE_DENSITY = "density";
707 * sort the alignment using the features on each sequence found between start
708 * and stop with the given featureLabel (and optional group qualifier)
710 * @param featureLabel
715 * (-1 to include non-positional features)
717 * (-1 to only sort on non-positional features)
719 * - aligned sequences containing features
721 * - one of the string constants FEATURE_SCORE, FEATURE_LABEL,
724 public static void sortByFeature(String featureLabel, String groupLabel,
725 int start, int stop, AlignmentI alignment, String method)
727 sortByFeature(featureLabel == null ? null : new String[]
728 { featureLabel }, groupLabel == null ? null : new String[]
729 { groupLabel }, start, stop, alignment, method);
732 private static boolean containsIgnoreCase(final String lab,
743 for (int q = 0; q < labs.length; q++)
745 if (labs[q] != null && lab.equalsIgnoreCase(labs[q]))
753 public static void sortByFeature(String[] featureLabels,
754 String[] groupLabels, int start, int stop, AlignmentI alignment,
757 if (method != FEATURE_SCORE && method != FEATURE_LABEL
758 && method != FEATURE_DENSITY)
761 "Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY.");
763 boolean ignoreScore = method != FEATURE_SCORE;
764 StringBuffer scoreLabel = new StringBuffer();
765 scoreLabel.append(start + stop + method);
766 // This doesn't quite work yet - we'd like to have a canonical ordering that
767 // can be preserved from call to call
768 for (int i = 0; featureLabels != null && i < featureLabels.length; i++)
770 scoreLabel.append(featureLabels[i] == null ? "null"
773 for (int i = 0; groupLabels != null && i < groupLabels.length; i++)
775 scoreLabel.append(groupLabels[i] == null ? "null" : groupLabels[i]);
777 SequenceI[] seqs = alignment.getSequencesArray();
779 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
781 int hasScores = 0; // number of scores present on set
782 double[] scores = new double[seqs.length];
783 int[] seqScores = new int[seqs.length];
784 Object[] feats = new Object[seqs.length];
785 double min = 0, max = 0;
786 for (int i = 0; i < seqs.length; i++)
788 SequenceFeature[] sf = seqs[i].getSequenceFeatures();
789 if (sf == null && seqs[i].getDatasetSequence() != null)
791 sf = seqs[i].getDatasetSequence().getSequenceFeatures();
795 sf = new SequenceFeature[0];
799 SequenceFeature[] tmp = new SequenceFeature[sf.length];
800 for (int s = 0; s < tmp.length; s++)
806 int sstart = (start == -1) ? start : seqs[i].findPosition(start);
807 int sstop = (stop == -1) ? stop : seqs[i].findPosition(stop);
811 for (int f = 0; f < sf.length; f++)
813 // filter for selection criteria
815 // ignore features outwith alignment start-stop positions.
816 (sf[f].end < sstart || sf[f].begin > sstop) ||
817 // or ignore based on selection criteria
818 (featureLabels != null && !AlignmentSorter
819 .containsIgnoreCase(sf[f].type, featureLabels))
820 || (groupLabels != null
821 // problem here: we cannot eliminate null feature group features
822 && (sf[f].getFeatureGroup() != null && !AlignmentSorter
823 .containsIgnoreCase(sf[f].getFeatureGroup(),
826 // forget about this feature
832 // or, also take a look at the scores if necessary.
833 if (!ignoreScore && sf[f].getScore() != Float.NaN)
835 if (seqScores[i] == 0)
841 scores[i] += sf[f].getScore(); // take the first instance of this
846 SequenceFeature[] fs;
847 feats[i] = fs = new SequenceFeature[n];
851 for (int f = 0; f < sf.length; f++)
855 ((SequenceFeature[]) feats[i])[n++] = sf[f];
858 if (method == FEATURE_LABEL)
860 // order the labels by alphabet
861 String[] labs = new String[fs.length];
862 for (int l = 0; l < labs.length; l++)
864 labs[l] = (fs[l].getDescription() != null ? fs[l]
865 .getDescription() : fs[l].getType());
867 jalview.util.QuickSort.sort(labs, ((Object[]) feats[i]));
872 // compute average score
873 scores[i] /= seqScores[i];
874 // update the score bounds.
877 max = min = scores[i];
893 if (method == FEATURE_SCORE)
897 return; // do nothing - no scores present to sort by.
900 if (hasScores < seqs.length)
902 for (int i = 0; i < seqs.length; i++)
906 scores[i] = (max + 1 + i);
910 int nf = (feats[i] == null) ? 0
911 : ((SequenceFeature[]) feats[i]).length;
912 // System.err.println("Sorting on Score: seq "+seqs[i].getName()+
913 // " Feats: "+nf+" Score : "+scores[i]);
918 jalview.util.QuickSort.sort(scores, seqs);
920 else if (method == FEATURE_DENSITY)
923 // break ties between equivalent numbers for adjacent sequences by adding
924 // 1/Nseq*i on the original order
925 double fr = 0.9 / (1.0 * seqs.length);
926 for (int i = 0; i < seqs.length; i++)
929 scores[i] = (0.05 + fr * i)
930 + (nf = ((feats[i] == null) ? 0.0
931 : 1.0 * ((SequenceFeature[]) feats[i]).length));
932 // System.err.println("Sorting on Density: seq "+seqs[i].getName()+
933 // " Feats: "+nf+" Score : "+scores[i]);
935 jalview.util.QuickSort.sort(scores, seqs);
939 if (method == FEATURE_LABEL)
941 throw new Error("Not yet implemented.");
944 if (lastSortByFeatureScore == null
945 || !scoreLabel.toString().equals(lastSortByFeatureScore))
947 sortByFeatureScoreAscending = true;
951 sortByFeatureScoreAscending = !sortByFeatureScoreAscending;
953 if (sortByFeatureScoreAscending)
955 setOrder(alignment, seqs);
959 setReverseOrder(alignment, seqs);
961 lastSortByFeatureScore = scoreLabel.toString();