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