JAL-3081 JAL-3199 no auto-sort of annotations after manual reordering
[jalview.git] / src / jalview / analysis / AnnotationSorter.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.analysis;
22
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.SequenceI;
26
27 import java.util.Arrays;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.Map;
31
32 /**
33  * A helper class to sort all annotations associated with an alignment in
34  * various ways.
35  * 
36  * @author gmcarstairs
37  *
38  */
39 public class AnnotationSorter
40 {
41
42   /**
43    * enum for annotation sort options. The text description is used in the
44    * Preferences drop-down options. The enum name is saved in the preferences
45    * file.
46    * 
47    * @author gmcarstairs
48    *
49    */
50   public enum SequenceAnnotationOrder
51   {
52     // Text descriptions surface in the Preferences Sort by... options
53     SEQUENCE_AND_LABEL("Sequence"), LABEL_AND_SEQUENCE("Label"),
54     NONE("No sort"),
55
56     /**
57      * custom is set if user drags to reorder annotations
58      */
59     CUSTOM("Customised");
60
61     private String description;
62
63     private SequenceAnnotationOrder(String s)
64     {
65       description = s;
66     }
67
68     @Override
69     public String toString()
70     {
71       return description;
72     }
73
74     public static SequenceAnnotationOrder forDescription(String d)
75     {
76       for (SequenceAnnotationOrder order : values())
77       {
78         if (order.toString().equals(d))
79         {
80           return order;
81         }
82       }
83       return null;
84     }
85   }
86
87   // the alignment with respect to which annotations are sorted
88   private final AlignmentI alignment;
89
90   // user preference for placement of non-sequence annotations
91   private boolean showAutocalcAbove;
92
93   // working map of sequence index in alignment
94   private final Map<SequenceI, Integer> sequenceIndices = new HashMap<>();
95
96   /**
97    * Constructor given an alignment and the location (top or bottom) of
98    * Consensus and similar.
99    * 
100    * @param alignmentI
101    * @param showAutocalculatedAbove
102    */
103   public AnnotationSorter(AlignmentI alignmentI,
104           boolean showAutocalculatedAbove)
105   {
106     this.alignment = alignmentI;
107     this.showAutocalcAbove = showAutocalculatedAbove;
108   }
109
110   /**
111    * Default comparator sorts as follows by annotation type within sequence
112    * order:
113    * <ul>
114    * <li>annotations with a reference to a sequence in the alignment are sorted
115    * on sequence ordering</li>
116    * <li>other annotations go 'at the end', with their mutual order
117    * unchanged</li>
118    * <li>within the same sequence ref, sort by label (non-case-sensitive)</li>
119    * </ul>
120    */
121   private final Comparator<? super AlignmentAnnotation> bySequenceAndLabel = new Comparator<AlignmentAnnotation>()
122   {
123     @Override
124     public int compare(AlignmentAnnotation o1, AlignmentAnnotation o2)
125     {
126       if (o1 == null && o2 == null)
127       {
128         return 0;
129       }
130       if (o1 == null)
131       {
132         return -1;
133       }
134       if (o2 == null)
135       {
136         return 1;
137       }
138
139       // TODO how to treat sequence-related autocalculated annotation
140       boolean o1auto = o1.autoCalculated && o1.sequenceRef == null;
141       boolean o2auto = o2.autoCalculated && o2.sequenceRef == null;
142       /*
143        * Ignore label (keep existing ordering) for
144        * Conservation/Quality/Consensus etc
145        */
146       if (o1auto && o2auto)
147       {
148         return 0;
149       }
150
151       /*
152        * Sort autocalculated before or after sequence-related.
153        */
154       if (o1auto)
155       {
156         return showAutocalcAbove ? -1 : 1;
157       }
158       if (o2auto)
159       {
160         return showAutocalcAbove ? 1 : -1;
161       }
162       int sequenceOrder = compareSequences(o1, o2);
163       return sequenceOrder == 0 ? compareLabels(o1, o2) : sequenceOrder;
164     }
165
166     @Override
167     public String toString()
168     {
169       return "Sort by sequence and label";
170     }
171   };
172
173   /**
174    * This comparator sorts as follows by sequence order within annotation type
175    * <ul>
176    * <li>annotations with a reference to a sequence in the alignment are sorted
177    * on label (non-case-sensitive)</li>
178    * <li>other annotations go 'at the end', with their mutual order
179    * unchanged</li>
180    * <li>within the same label, sort by order of the related sequences</li>
181    * </ul>
182    */
183   private final Comparator<? super AlignmentAnnotation> byLabelAndSequence = new Comparator<AlignmentAnnotation>()
184   {
185     @Override
186     public int compare(AlignmentAnnotation o1, AlignmentAnnotation o2)
187     {
188       if (o1 == null && o2 == null)
189       {
190         return 0;
191       }
192       if (o1 == null)
193       {
194         return -1;
195       }
196       if (o2 == null)
197       {
198         return 1;
199       }
200
201       // TODO how to treat sequence-related autocalculated annotation
202       boolean o1auto = o1.autoCalculated && o1.sequenceRef == null;
203       boolean o2auto = o2.autoCalculated && o2.sequenceRef == null;
204       /*
205        * Ignore label (keep existing ordering) for
206        * Conservation/Quality/Consensus etc
207        */
208       if (o1auto && o2auto)
209       {
210         return 0;
211       }
212
213       /*
214        * Sort autocalculated before or after sequence-related.
215        */
216       if (o1auto)
217       {
218         return showAutocalcAbove ? -1 : 1;
219       }
220       if (o2auto)
221       {
222         return showAutocalcAbove ? 1 : -1;
223       }
224       int labelOrder = compareLabels(o1, o2);
225       return labelOrder == 0 ? compareSequences(o1, o2) : labelOrder;
226     }
227
228     @Override
229     public String toString()
230     {
231       return "Sort by label and sequence";
232     }
233   };
234
235   /**
236    * noSort leaves sort order unchanged, within sequence- and autocalculated
237    * annotations, but may switch the ordering of these groups. Note this is
238    * guaranteed (at least in Java 7) as Arrays.sort() is guaranteed to be
239    * 'stable' (not change ordering of equal items).
240    */
241   private Comparator<? super AlignmentAnnotation> noSort = new Comparator<AlignmentAnnotation>()
242   {
243     @Override
244     public int compare(AlignmentAnnotation o1, AlignmentAnnotation o2)
245     {
246       // TODO how to treat sequence-related autocalculated annotation
247       boolean o1auto = o1.autoCalculated && o1.sequenceRef == null;
248       boolean o2auto = o2.autoCalculated && o2.sequenceRef == null;
249       // TODO skip this test to allow customised ordering of all annotations
250       // - needs a third option: place autocalculated first / last / none
251       if (o1 != null && o2 != null)
252       {
253         if (o1auto && !o2auto)
254         {
255           return showAutocalcAbove ? -1 : 1;
256         }
257         if (!o1auto && o2auto)
258         {
259           return showAutocalcAbove ? 1 : -1;
260         }
261       }
262       return 0;
263     }
264
265     @Override
266     public String toString()
267     {
268       return "No sort";
269     }
270   };
271
272   /**
273    * Sort by the specified ordering of sequence-specific annotations.
274    * 
275    * @param alignmentAnnotations
276    * @param order
277    */
278   public void sort(AlignmentAnnotation[] alignmentAnnotations,
279           SequenceAnnotationOrder order)
280   {
281     if (alignmentAnnotations == null
282             || order == SequenceAnnotationOrder.CUSTOM)
283     {
284       return;
285     }
286     // cache 'alignment sequence position' for the annotations
287     saveSequenceIndices(alignmentAnnotations);
288
289     Comparator<? super AlignmentAnnotation> comparator = getComparator(
290             order);
291
292     if (alignmentAnnotations != null)
293     {
294       synchronized (alignmentAnnotations)
295       {
296         Arrays.sort(alignmentAnnotations, comparator);
297       }
298     }
299   }
300
301   /**
302    * Calculate and save in a temporary map the position of each annotation's
303    * sequence (if it has one) in the alignment. Faster to do this once than for
304    * every annotation comparison.
305    * 
306    * @param alignmentAnnotations
307    */
308   private void saveSequenceIndices(
309           AlignmentAnnotation[] alignmentAnnotations)
310   {
311     sequenceIndices.clear();
312     for (AlignmentAnnotation ann : alignmentAnnotations)
313     {
314       SequenceI seq = ann.sequenceRef;
315       if (seq != null)
316       {
317         int index = AlignmentUtils.getSequenceIndex(alignment, seq);
318         sequenceIndices.put(seq, index);
319       }
320     }
321   }
322
323   /**
324    * Get the comparator for the specified sort order.
325    * 
326    * @param order
327    * @return
328    */
329   private Comparator<? super AlignmentAnnotation> getComparator(
330           SequenceAnnotationOrder order)
331   {
332     if (order == null)
333     {
334       return noSort;
335     }
336     switch (order)
337     {
338     case NONE:
339       return this.noSort;
340     case SEQUENCE_AND_LABEL:
341       return this.bySequenceAndLabel;
342     case LABEL_AND_SEQUENCE:
343       return this.byLabelAndSequence;
344     default:
345       throw new UnsupportedOperationException(order.toString());
346     }
347   }
348
349   /**
350    * Non-case-sensitive comparison of annotation labels. Returns zero if either
351    * argument is null.
352    * 
353    * @param o1
354    * @param o2
355    * @return
356    */
357   private int compareLabels(AlignmentAnnotation o1, AlignmentAnnotation o2)
358   {
359     if (o1 == null || o2 == null)
360     {
361       return 0;
362     }
363     String label1 = o1.label;
364     String label2 = o2.label;
365     if (label1 == null && label2 == null)
366     {
367       return 0;
368     }
369     if (label1 == null)
370     {
371       return -1;
372     }
373     if (label2 == null)
374     {
375       return 1;
376     }
377     return label1.toUpperCase().compareTo(label2.toUpperCase());
378   }
379
380   /**
381    * Comparison based on position of associated sequence (if any) in the
382    * alignment. Returns zero if either argument is null.
383    * 
384    * @param o1
385    * @param o2
386    * @return
387    */
388   private int compareSequences(AlignmentAnnotation o1,
389           AlignmentAnnotation o2)
390   {
391     SequenceI seq1 = o1.sequenceRef;
392     SequenceI seq2 = o2.sequenceRef;
393     if (seq1 == null && seq2 == null)
394     {
395       return 0;
396     }
397     /*
398      * Sort non-sequence-related before or after sequence-related.
399      */
400     if (seq1 == null)
401     {
402       return showAutocalcAbove ? -1 : 1;
403     }
404     if (seq2 == null)
405     {
406       return showAutocalcAbove ? 1 : -1;
407     }
408     // get sequence index - but note -1 means 'at end' so needs special handling
409     int index1 = sequenceIndices.get(seq1);
410     int index2 = sequenceIndices.get(seq2);
411     if (index1 == index2)
412     {
413       return 0;
414     }
415     if (index1 == -1)
416     {
417       return -1;
418     }
419     if (index2 == -1)
420     {
421       return 1;
422     }
423     return Integer.compare(index1, index2);
424   }
425 }