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