2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 package jalview.analysis;
23 import jalview.datamodel.*;
24 import jalview.util.*;
27 * Routines for manipulating the order of a multiple sequence alignment TODO:
28 * this class retains some global states concerning sort-order which should be
29 * made attributes for the caller's alignment visualization. TODO: refactor to
30 * allow a subset of selected sequences to be sorted within the context of a
31 * whole alignment. Sort method template is: SequenceI[] tobesorted, [ input
32 * data mapping to each tobesorted element to use ], Alignment context of
33 * tobesorted that are to be re-ordered, boolean sortinplace, [special data - ie
34 * seuqence to be sorted w.r.t.]) sortinplace implies that the sorted vector
35 * resulting from applying the operation to tobesorted should be mapped back to
36 * the original positions in alignment. Otherwise, normal behaviour is to re
37 * order alignment so that tobesorted is sorted and grouped together starting
38 * from the first tobesorted position in the alignment. e.g. (a,tb2,b,tb1,c,tb3
39 * becomes a,tb1,tb2,tb3,b,c)
41 public class AlignmentSorter
43 static boolean sortIdAscending = true;
45 static int lastGroupHash = 0;
47 static boolean sortGroupAscending = true;
49 static AlignmentOrder lastOrder = null;
51 static boolean sortOrderAscending = true;
53 static NJTree lastTree = null;
55 static boolean sortTreeAscending = true;
58 * last Annotation Label used by sortByScore
60 private static String lastSortByScore;
63 * compact representation of last arguments to SortByFeatureScore
65 private static String lastSortByFeatureScore;
67 private static boolean sortLengthAscending;
70 * Sort by Percentage Identity w.r.t. s
77 * sequences from align that are to be sorted.
79 public static void sortByPID(AlignmentI align, SequenceI s,
82 int nSeq = align.getHeight();
84 float[] scores = new float[nSeq];
85 SequenceI[] seqs = new SequenceI[nSeq];
87 for (int i = 0; i < nSeq; i++)
89 scores[i] = Comparison.PID(align.getSequenceAt(i)
90 .getSequenceAsString(), s.getSequenceAsString());
91 seqs[i] = align.getSequenceAt(i);
94 QuickSort.sort(scores, 0, scores.length - 1, seqs);
96 setReverseOrder(align, seqs);
100 * Reverse the order of the sort
107 private static void setReverseOrder(AlignmentI align, SequenceI[] seqs)
109 int nSeq = seqs.length;
119 len = (nSeq + 1) / 2;
122 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
123 for (int i = 0; i < len; i++)
125 // SequenceI tmp = seqs[i];
126 align.getSequences().setElementAt(seqs[nSeq - i - 1], i);
127 align.getSequences().setElementAt(seqs[i], nSeq - i - 1);
132 * Sets the Alignment object with the given sequences
135 * Alignment object to be updated
137 * sequences as a vector
139 private static void setOrder(AlignmentI align, Vector tmp)
141 setOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
145 * Sets the Alignment object with the given sequences
150 * sequences as an array
152 public static void setOrder(AlignmentI align, SequenceI[] seqs)
154 // NOTE: DO NOT USE align.setSequenceAt() here - it will NOT work
155 Vector algn = align.getSequences();
156 Vector tmp = new Vector();
158 for (int i = 0; i < seqs.length; i++)
160 if (algn.contains(seqs[i]))
162 tmp.addElement(seqs[i]);
166 algn.removeAllElements();
167 // User may have hidden seqs, then clicked undo or redo
168 for (int i = 0; i < tmp.size(); i++)
170 algn.addElement(tmp.elementAt(i));
176 * Sorts by ID. Numbers are sorted before letters.
179 * The alignment object to sort
181 public static void sortByID(AlignmentI align)
183 int nSeq = align.getHeight();
185 String[] ids = new String[nSeq];
186 SequenceI[] seqs = new SequenceI[nSeq];
188 for (int i = 0; i < nSeq; i++)
190 ids[i] = align.getSequenceAt(i).getName();
191 seqs[i] = align.getSequenceAt(i);
194 QuickSort.sort(ids, seqs);
198 setReverseOrder(align, seqs);
202 setOrder(align, seqs);
205 sortIdAscending = !sortIdAscending;
208 * Sorts by sequence length
211 * The alignment object to sort
213 public static void sortByLength(AlignmentI align)
215 int nSeq = align.getHeight();
217 float[] length = new float[nSeq];
218 SequenceI[] seqs = new SequenceI[nSeq];
220 for (int i = 0; i < nSeq; i++)
222 seqs[i] = align.getSequenceAt(i);
223 length[i] = (float) (seqs[i].getEnd()-seqs[i].getStart());
226 QuickSort.sort(length, seqs);
228 if (sortLengthAscending)
230 setReverseOrder(align, seqs);
234 setOrder(align, seqs);
237 sortLengthAscending = !sortLengthAscending;
241 * Sorts the alignment by size of group. <br>
242 * Maintains the order of sequences in each group by order in given alignment
246 * sorts the given alignment object by group
248 public static void sortByGroup(AlignmentI align)
250 // MAINTAINS ORIGNAL SEQUENCE ORDER,
251 // ORDERS BY GROUP SIZE
252 Vector groups = new Vector();
254 if (groups.hashCode() != lastGroupHash)
256 sortGroupAscending = true;
257 lastGroupHash = groups.hashCode();
261 sortGroupAscending = !sortGroupAscending;
264 // SORTS GROUPS BY SIZE
265 // ////////////////////
266 for (int i = 0; i < align.getGroups().size(); i++)
268 SequenceGroup sg = (SequenceGroup) align.getGroups().elementAt(i);
270 for (int j = 0; j < groups.size(); j++)
272 SequenceGroup sg2 = (SequenceGroup) groups.elementAt(j);
274 if (sg.getSize() > sg2.getSize())
276 groups.insertElementAt(sg, j);
282 if (!groups.contains(sg))
284 groups.addElement(sg);
288 // NOW ADD SEQUENCES MAINTAINING ALIGNMENT ORDER
289 // /////////////////////////////////////////////
290 Vector seqs = new Vector();
292 for (int i = 0; i < groups.size(); i++)
294 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
295 SequenceI[] orderedseqs = sg.getSequencesInOrder(align);
297 for (int j = 0; j < orderedseqs.length; j++)
299 seqs.addElement(orderedseqs[j]);
303 if (sortGroupAscending)
305 setOrder(align, seqs);
309 setReverseOrder(align,
310 vectorSubsetToArray(seqs, align.getSequences()));
315 * Converts Vector to array. java 1.18 does not have Vector.toArray()
318 * Vector of SequenceI objects
320 * @return array of Sequence[]
322 private static SequenceI[] vectorToArray(Vector tmp)
324 SequenceI[] seqs = new SequenceI[tmp.size()];
326 for (int i = 0; i < tmp.size(); i++)
328 seqs[i] = (SequenceI) tmp.elementAt(i);
342 * @return DOCUMENT ME!
344 private static SequenceI[] vectorSubsetToArray(Vector tmp, Vector mask)
346 Vector seqs = new Vector();
348 boolean[] tmask = new boolean[mask.size()];
350 for (i = 0; i < mask.size(); i++)
355 for (i = 0; i < tmp.size(); i++)
357 Object sq = tmp.elementAt(i);
359 if (mask.contains(sq) && tmask[mask.indexOf(sq)])
361 tmask[mask.indexOf(sq)] = false;
366 for (i = 0; i < tmask.length; i++)
370 seqs.addElement(mask.elementAt(i));
374 return vectorToArray(seqs);
378 * Sorts by a given AlignmentOrder object
383 * specified order for alignment
385 public static void sortBy(AlignmentI align, AlignmentOrder order)
387 // Get an ordered vector of sequences which may also be present in align
388 Vector tmp = order.getOrder();
390 if (lastOrder == order)
392 sortOrderAscending = !sortOrderAscending;
396 sortOrderAscending = true;
399 if (sortOrderAscending)
401 setOrder(align, tmp);
405 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
417 * @return DOCUMENT ME!
419 private static Vector getOrderByTree(AlignmentI align, NJTree tree)
421 int nSeq = align.getHeight();
423 Vector tmp = new Vector();
425 tmp = _sortByTree(tree.getTopNode(), tmp, align.getSequences());
427 if (tmp.size() != nSeq)
429 // TODO: JBPNote - decide if this is always an error
430 // (eg. not when a tree is associated to another alignment which has more
432 if (tmp.size() < nSeq)
434 addStrays(align, tmp);
437 if (tmp.size() != nSeq)
439 System.err.println("ERROR: tmp.size()=" + tmp.size() + " != nseq="
440 + nSeq + " in getOrderByTree");
448 * Sorts the alignment by a given tree
455 public static void sortByTree(AlignmentI align, NJTree tree)
457 Vector tmp = getOrderByTree(align, tree);
459 // tmp should properly permute align with tree.
460 if (lastTree != tree)
462 sortTreeAscending = true;
467 sortTreeAscending = !sortTreeAscending;
470 if (sortTreeAscending)
472 setOrder(align, tmp);
476 setReverseOrder(align, vectorSubsetToArray(tmp, align.getSequences()));
488 private static void addStrays(AlignmentI align, Vector seqs)
490 int nSeq = align.getHeight();
492 for (int i = 0; i < nSeq; i++)
494 if (!seqs.contains(align.getSequenceAt(i)))
496 seqs.addElement(align.getSequenceAt(i));
500 if (nSeq != seqs.size())
503 .println("ERROR: Size still not right even after addStrays");
517 * @return DOCUMENT ME!
519 private static Vector _sortByTree(SequenceNode node, Vector tmp,
527 SequenceNode left = (SequenceNode) node.left();
528 SequenceNode right = (SequenceNode) node.right();
530 if ((left == null) && (right == null))
532 if (!node.isPlaceholder() && (node.element() != null))
534 if (node.element() instanceof SequenceI)
536 if (!tmp.contains(node.element()))
538 tmp.addElement((SequenceI) node.element());
547 _sortByTree(left, tmp, seqset);
548 _sortByTree(right, tmp, seqset);
555 // Alignment.sortBy(OrderObj) - sequence of sequence pointer refs in
560 * recover the order of sequences given by the safe numbering scheme introducd
561 * SeqsetUtils.uniquify.
563 public static void recoverOrder(SequenceI[] alignment)
565 float[] ids = new float[alignment.length];
567 for (int i = 0; i < alignment.length; i++)
569 ids[i] = (new Float(alignment[i].getName().substring(8)))
573 jalview.util.QuickSort.sort(ids, alignment);
577 * Sort sequence in order of increasing score attribute for annotation with a
578 * particular scoreLabel. Or reverse if same label was used previously
581 * exact label for sequence associated AlignmentAnnotation
582 * scores to use for sorting.
584 * sequences to be sorted
586 public static void sortByAnnotationScore(String scoreLabel,
587 AlignmentI alignment)
589 SequenceI[] seqs = alignment.getSequencesArray();
590 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
592 int hasScores = 0; // number of scores present on set
593 double[] scores = new double[seqs.length];
594 double min = 0, max = 0;
595 for (int i = 0; i < seqs.length; i++)
597 AlignmentAnnotation[] scoreAnn = seqs[i].getAnnotation(scoreLabel);
598 if (scoreAnn != null)
602 scores[i] = scoreAnn[0].getScore(); // take the first instance of this
606 max = min = scores[i];
627 return; // do nothing - no scores present to sort by.
629 if (hasScores < seqs.length)
631 for (int i = 0; i < seqs.length; i++)
635 scores[i] = (max + i+1.0);
640 jalview.util.QuickSort.sort(scores, seqs);
641 if (lastSortByScore != scoreLabel)
643 lastSortByScore = scoreLabel;
644 setOrder(alignment, seqs);
648 setReverseOrder(alignment, seqs);
652 * types of feature ordering:
653 * Sort by score : average score - or total score - over all features in region
654 * Sort by feature label text: (or if null - feature type text) - numerical or alphabetical
655 * Sort by feature density: based on counts - ignoring individual text or scores for each feature
657 public static String FEATURE_SCORE="average_score";
658 public static String FEATURE_LABEL="text";
659 public static String FEATURE_DENSITY="density";
662 * sort the alignment using the features on each sequence found between start and stop with the given featureLabel (and optional group qualifier)
663 * @param featureLabel (may not be null)
664 * @param groupLabel (may be null)
665 * @param start (-1 to include non-positional features)
666 * @param stop (-1 to only sort on non-positional features)
667 * @param alignment - aligned sequences containing features
668 * @param method - one of the string constants FEATURE_SCORE, FEATURE_LABEL, FEATURE_DENSITY
670 public static void sortByFeature(String featureLabel, String groupLabel, int start, int stop,
671 AlignmentI alignment, String method)
673 sortByFeature(featureLabel==null ? null : new String[] {featureLabel},
674 groupLabel==null ? null : new String[] {groupLabel}, start, stop, alignment, method);
676 private static boolean containsIgnoreCase(final String lab, final String[] labs)
686 for (int q=0;q<labs.length;q++)
688 if (labs[q]!=null && lab.equalsIgnoreCase(labs[q]))
695 public static void sortByFeature(String[] featureLabels, String[] groupLabels, int start, int stop,
696 AlignmentI alignment, String method)
698 if (method!=FEATURE_SCORE && method!=FEATURE_LABEL && method!=FEATURE_DENSITY)
700 throw new Error("Implementation Error - sortByFeature method must be one of FEATURE_SCORE, FEATURE_LABEL or FEATURE_DENSITY.");
702 boolean ignoreScore=method!=FEATURE_SCORE;
703 StringBuffer scoreLabel = new StringBuffer();
704 scoreLabel.append(start+stop+method);
705 // This doesn't work yet - we'd like to have a canonical ordering that can be preserved from call to call
706 for (int i=0;featureLabels!=null && i<featureLabels.length; i++)
708 scoreLabel.append(featureLabels[i]==null ? "null" : featureLabels[i]);
710 for (int i=0;groupLabels!=null && i<groupLabels.length; i++)
712 scoreLabel.append(groupLabels[i]==null ? "null" : groupLabels[i]);
714 SequenceI[] seqs = alignment.getSequencesArray();
716 boolean[] hasScore = new boolean[seqs.length]; // per sequence score
718 int hasScores = 0; // number of scores present on set
719 double[] scores = new double[seqs.length];
720 int[] seqScores = new int[seqs.length];
721 Object[] feats = new Object[seqs.length];
722 double min = 0, max = 0;
723 for (int i = 0; i < seqs.length; i++)
725 SequenceFeature[] sf = seqs[i].getSequenceFeatures();
726 if (sf==null && seqs[i].getDatasetSequence()!=null)
728 sf = seqs[i].getDatasetSequence().getSequenceFeatures();
732 sf = new SequenceFeature[0];
734 SequenceFeature[] tmp = new SequenceFeature[sf.length];
735 for (int s=0; s<tmp.length;s++)
741 int sstart = (start==-1) ? start : seqs[i].findPosition(start);
742 int sstop = (stop==-1) ? stop : seqs[i].findPosition(stop);
746 for (int f=0;f<sf.length;f++)
748 // filter for selection criteria
750 // ignore features outwith alignment start-stop positions.
751 (sf[f].end < sstart || sf[f].begin > sstop)
753 // or ignore based on selection criteria
754 (featureLabels != null && !AlignmentSorter.containsIgnoreCase(sf[f].type, featureLabels))
755 || (groupLabels != null
756 // problem here: we cannot eliminate null feature group features
757 && (sf[f].getFeatureGroup() != null
758 && !AlignmentSorter.containsIgnoreCase(sf[f].getFeatureGroup(), groupLabels))))
760 // forget about this feature
764 // or, also take a look at the scores if necessary.
765 if (!ignoreScore && sf[f].getScore()!=Float.NaN)
773 scores[i] += sf[f].getScore(); // take the first instance of this
778 SequenceFeature[] fs;
779 feats[i] = fs = new SequenceFeature[n];
783 for (int f=0;f<sf.length;f++)
787 ((SequenceFeature[]) feats[i])[n++] = sf[f];
790 if (method==FEATURE_LABEL)
792 // order the labels by alphabet
793 String[] labs = new String[fs.length];
794 for (int l=0;l<labs.length; l++)
796 labs[l] = (fs[l].getDescription()!=null ? fs[l].getDescription() : fs[l].getType());
798 jalview.util.QuickSort.sort(labs, ((Object[]) feats[i]));
803 // compute average score
804 scores[i]/=seqScores[i];
805 // update the score bounds.
808 max = min = scores[i];
824 if (method==FEATURE_SCORE)
828 return; // do nothing - no scores present to sort by.
831 if (hasScores < seqs.length)
833 for (int i = 0; i < seqs.length; i++)
837 scores[i] = (max + i);
839 int nf=(feats[i]==null) ? 0 :((SequenceFeature[]) feats[i]).length;
840 System.err.println("Sorting on Score: seq "+seqs[i].getName()+ " Feats: "+nf+" Score : "+scores[i]);
845 jalview.util.QuickSort.sort(scores, seqs);
848 if (method==FEATURE_DENSITY)
851 // break ties between equivalent numbers for adjacent sequences by adding 1/Nseq*i on the original order
852 double fr = 0.9/(1.0*seqs.length);
853 for (int i=0;i<seqs.length; i++)
856 scores[i] = (0.05+fr*i)+(nf=((feats[i]==null) ? 0.0 :1.0*((SequenceFeature[]) feats[i]).length));
857 System.err.println("Sorting on Density: seq "+seqs[i].getName()+ " Feats: "+nf+" Score : "+scores[i]);
859 jalview.util.QuickSort.sort(scores, seqs);
862 if (method==FEATURE_LABEL)
864 throw new Error("Not yet implemented.");
867 if (lastSortByFeatureScore ==null || scoreLabel.equals(lastSortByFeatureScore))
869 setOrder(alignment, seqs);
873 setReverseOrder(alignment, seqs);
875 lastSortByFeatureScore = scoreLabel.toString();