JAL-3081 more efficient algorithm for annotation ordering by sequence
[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
287     /*
288      * cache 'alignment sequence positions' if required for sorting
289      */
290     if (order == SequenceAnnotationOrder.SEQUENCE_AND_LABEL
291             || order == SequenceAnnotationOrder.LABEL_AND_SEQUENCE)
292     {
293       saveSequenceIndices(alignmentAnnotations);
294     }
295
296     Comparator<? super AlignmentAnnotation> comparator = getComparator(
297             order);
298
299     if (alignmentAnnotations != null)
300     {
301       synchronized (alignmentAnnotations)
302       {
303         Arrays.sort(alignmentAnnotations, comparator);
304       }
305     }
306   }
307
308   /**
309    * Calculate and save in a temporary map the position of each annotation's
310    * sequence (if it has one) in the alignment. Faster to do this once than for
311    * every annotation comparison.
312    * 
313    * @param alignmentAnnotations
314    */
315   private void saveSequenceIndices(
316           AlignmentAnnotation[] alignmentAnnotations)
317   {
318     sequenceIndices.clear();
319
320     Map<SequenceI, Integer> seqPositions = alignment.getSequencePositions();
321
322     for (AlignmentAnnotation ann : alignmentAnnotations)
323     {
324       SequenceI seq = ann.sequenceRef;
325       if (seq != null)
326       {
327         Integer index = seqPositions.get(seq);
328         if (index != null)
329         {
330           sequenceIndices.put(seq, index);
331         }
332       }
333     }
334   }
335
336   /**
337    * Get the comparator for the specified sort order.
338    * 
339    * @param order
340    * @return
341    */
342   private Comparator<? super AlignmentAnnotation> getComparator(
343           SequenceAnnotationOrder order)
344   {
345     if (order == null)
346     {
347       return noSort;
348     }
349     switch (order)
350     {
351     case NONE:
352       return this.noSort;
353     case SEQUENCE_AND_LABEL:
354       return this.bySequenceAndLabel;
355     case LABEL_AND_SEQUENCE:
356       return this.byLabelAndSequence;
357     default:
358       throw new UnsupportedOperationException(order.toString());
359     }
360   }
361
362   /**
363    * Non-case-sensitive comparison of annotation labels. Returns zero if either
364    * argument is null.
365    * 
366    * @param o1
367    * @param o2
368    * @return
369    */
370   private int compareLabels(AlignmentAnnotation o1, AlignmentAnnotation o2)
371   {
372     if (o1 == null || o2 == null)
373     {
374       return 0;
375     }
376     String label1 = o1.label;
377     String label2 = o2.label;
378     if (label1 == null && label2 == null)
379     {
380       return 0;
381     }
382     if (label1 == null)
383     {
384       return -1;
385     }
386     if (label2 == null)
387     {
388       return 1;
389     }
390     return label1.toUpperCase().compareTo(label2.toUpperCase());
391   }
392
393   /**
394    * Comparison based on position of associated sequence (if any) in the
395    * alignment
396    * 
397    * @param o1
398    * @param o2
399    * @return
400    */
401   private int compareSequences(AlignmentAnnotation o1,
402           AlignmentAnnotation o2)
403   {
404     SequenceI seq1 = o1.sequenceRef;
405     SequenceI seq2 = o2.sequenceRef;
406     if (seq1 == null && seq2 == null)
407     {
408       return 0;
409     }
410
411     /*
412      * Sort non-sequence-related before or after sequence-related
413      */
414     if (seq1 == null)
415     {
416       return showAutocalcAbove ? -1 : 1;
417     }
418     if (seq2 == null)
419     {
420       return showAutocalcAbove ? 1 : -1;
421     }
422
423     /*
424      * else sort by associated sequence position
425      */
426     Integer index1 = sequenceIndices.get(seq1);
427     Integer index2 = sequenceIndices.get(seq2);
428     if (index1 == null)
429     {
430       return index2 == null ? 0 : -1;
431     }
432     if (index2 == null)
433     {
434       return 1;
435     }
436     return Integer.compare(index1.intValue(), index2.intValue());
437   }
438 }