Merge branch 'bug/JAL-3120restoreFeatureColour' into merge/JAL-3120
[jalview.git] / src / jalview / datamodel / features / SequenceFeatures.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.datamodel.features;
22
23 import jalview.datamodel.SequenceFeature;
24 import jalview.io.gff.SequenceOntologyFactory;
25 import jalview.io.gff.SequenceOntologyI;
26
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Set;
34 import java.util.TreeMap;
35
36 import intervalstore.api.IntervalI;
37
38 /**
39  * A class that stores sequence features in a way that supports efficient
40  * querying by type and location (overlap). Intended for (but not limited to)
41  * storage of features for one sequence.
42  * 
43  * @author gmcarstairs
44  *
45  */
46 public class SequenceFeatures implements SequenceFeaturesI
47 {
48
49   /*
50    * map from feature type to structured store of features for that type
51    * null types are permitted (but not a good idea!)
52    */
53   private Map<String, FeatureStore> featureStore;
54
55   /**
56    * Constructor
57    */
58   public SequenceFeatures()
59   {
60     /*
61      * use a TreeMap so that features are returned in alphabetical order of type
62      * ? wrap as a synchronized map for add and delete operations
63      */
64     // featureStore = Collections
65     // .synchronizedSortedMap(new TreeMap<String, FeatureStore>());
66     featureStore = new TreeMap<>();
67   }
68
69   /**
70    * Constructor given a list of features
71    */
72   public SequenceFeatures(List<SequenceFeature> features)
73   {
74     this();
75     if (features != null)
76     {
77       for (SequenceFeature feature : features)
78       {
79         add(feature);
80       }
81     }
82   }
83
84   /**
85    * {@inheritDoc}
86    */
87   @Override
88   public boolean add(SequenceFeature sf)
89   {
90     String type = sf.getType();
91     if (type == null)
92     {
93       System.err.println("Feature type may not be null: " + sf.toString());
94       return false;
95     }
96
97     if (featureStore.get(type) == null)
98     {
99       featureStore.put(type, new FeatureStore());
100     }
101     return featureStore.get(type).addFeature(sf);
102   }
103
104   /**
105    * {@inheritDoc}
106    */
107   @Override
108   public List<SequenceFeature> findFeatures(int from, int to,
109           String... type)
110   {
111     List<SequenceFeature> result = new ArrayList<>();
112
113     for (FeatureStore featureSet : varargToTypes(type))
114     {
115       result.addAll(featureSet.findOverlappingFeatures(from, to));
116     }
117
118     return result;
119   }
120
121   /**
122    * {@inheritDoc}
123    */
124   @Override
125   public List<SequenceFeature> getAllFeatures(String... type)
126   {
127     List<SequenceFeature> result = new ArrayList<>();
128
129     result.addAll(getPositionalFeatures(type));
130
131     result.addAll(getNonPositionalFeatures());
132
133     return result;
134   }
135
136   /**
137    * {@inheritDoc}
138    */
139   @Override
140   public List<SequenceFeature> getFeaturesByOntology(String... ontologyTerm)
141   {
142     if (ontologyTerm == null || ontologyTerm.length == 0)
143     {
144       return new ArrayList<>();
145     }
146
147     Set<String> featureTypes = getFeatureTypes(ontologyTerm);
148     if (featureTypes.isEmpty())
149     {
150       /*
151        * no features of the specified type or any sub-type
152        */
153       return new ArrayList<>();
154     }
155
156     return getAllFeatures(featureTypes.toArray(new String[featureTypes
157             .size()]));
158   }
159
160   /**
161    * {@inheritDoc}
162    */
163   @Override
164   public int getFeatureCount(boolean positional, String... type)
165   {
166     int result = 0;
167
168     for (FeatureStore featureSet : varargToTypes(type))
169     {
170       result += featureSet.getFeatureCount(positional);
171     }
172     return result;
173   }
174
175   /**
176    * {@inheritDoc}
177    */
178   @Override
179   public int getTotalFeatureLength(String... type)
180   {
181     int result = 0;
182
183     for (FeatureStore featureSet : varargToTypes(type))
184     {
185       result += featureSet.getTotalFeatureLength();
186     }
187     return result;
188   }
189
190   /**
191    * {@inheritDoc}
192    */
193   @Override
194   public List<SequenceFeature> getPositionalFeatures(String... type)
195   {
196     List<SequenceFeature> result = new ArrayList<>();
197
198     for (FeatureStore featureSet : varargToTypes(type))
199     {
200       result.addAll(featureSet.getPositionalFeatures());
201     }
202     return result;
203   }
204
205   /**
206    * A convenience method that converts a vararg for feature types to an
207    * Iterable over matched feature sets in key order
208    * 
209    * @param type
210    * @return
211    */
212   protected Iterable<FeatureStore> varargToTypes(String... type)
213   {
214     if (type == null || type.length == 0)
215     {
216       /*
217        * no vararg parameter supplied - return all
218        */
219       return featureStore.values();
220     }
221
222     List<FeatureStore> types = new ArrayList<>();
223     List<String> args = Arrays.asList(type);
224     for (Entry<String, FeatureStore> featureType : featureStore.entrySet())
225     {
226       if (args.contains(featureType.getKey()))
227       {
228         types.add(featureType.getValue());
229       }
230     }
231     return types;
232   }
233
234   /**
235    * {@inheritDoc}
236    */
237   @Override
238   public List<SequenceFeature> getContactFeatures(String... type)
239   {
240     List<SequenceFeature> result = new ArrayList<>();
241
242     for (FeatureStore featureSet : varargToTypes(type))
243     {
244       result.addAll(featureSet.getContactFeatures());
245     }
246     return result;
247   }
248
249   /**
250    * {@inheritDoc}
251    */
252   @Override
253   public List<SequenceFeature> getNonPositionalFeatures(String... type)
254   {
255     List<SequenceFeature> result = new ArrayList<>();
256
257     for (FeatureStore featureSet : varargToTypes(type))
258     {
259       result.addAll(featureSet.getNonPositionalFeatures());
260     }
261     return result;
262   }
263
264   /**
265    * {@inheritDoc}
266    */
267   @Override
268   public boolean delete(SequenceFeature sf)
269   {
270     for (FeatureStore featureSet : featureStore.values())
271     {
272       if (featureSet.delete(sf))
273       {
274         return true;
275       }
276     }
277     return false;
278   }
279
280   /**
281    * {@inheritDoc}
282    */
283   @Override
284   public boolean hasFeatures()
285   {
286     for (FeatureStore featureSet : featureStore.values())
287     {
288       if (!featureSet.isEmpty())
289       {
290         return true;
291       }
292     }
293     return false;
294   }
295
296   /**
297    * {@inheritDoc}
298    */
299   @Override
300   public Set<String> getFeatureGroups(boolean positionalFeatures,
301           String... type)
302   {
303     Set<String> groups = new HashSet<>();
304
305     for (FeatureStore featureSet : varargToTypes(type))
306     {
307       groups.addAll(featureSet.getFeatureGroups(positionalFeatures));
308     }
309
310     return groups;
311   }
312
313   /**
314    * {@inheritDoc}
315    */
316   @Override
317   public Set<String> getFeatureTypesForGroups(boolean positionalFeatures,
318           String... groups)
319   {
320     Set<String> result = new HashSet<>();
321
322     for (Entry<String, FeatureStore> featureType : featureStore.entrySet())
323     {
324       Set<String> featureGroups = featureType.getValue().getFeatureGroups(
325               positionalFeatures);
326       for (String group : groups)
327       {
328         if (featureGroups.contains(group))
329         {
330           /*
331            * yes this feature type includes one of the query groups
332            */
333           result.add(featureType.getKey());
334           break;
335         }
336       }
337     }
338
339     return result;
340   }
341
342   /**
343    * {@inheritDoc}
344    */
345   @Override
346   public Set<String> getFeatureTypes(String... soTerm)
347   {
348     Set<String> types = new HashSet<>();
349     for (Entry<String, FeatureStore> entry : featureStore.entrySet())
350     {
351       String type = entry.getKey();
352       if (!entry.getValue().isEmpty() && isOntologyTerm(type, soTerm))
353       {
354         types.add(type);
355       }
356     }
357     return types;
358   }
359
360   /**
361    * Answers true if the given type matches one of the specified terms (or is a
362    * sub-type of one in the Sequence Ontology), or if no terms are supplied.
363    * Answers false if filter terms are specified and the given term does not
364    * match any of them.
365    * 
366    * @param type
367    * @param soTerm
368    * @return
369    */
370   protected boolean isOntologyTerm(String type, String... soTerm)
371   {
372     if (soTerm == null || soTerm.length == 0)
373     {
374       return true;
375     }
376     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
377     for (String term : soTerm)
378     {
379       if (type.equals(term) || so.isA(type, term))
380       {
381         return true;
382       }
383     }
384     return false;
385   }
386
387   /**
388    * {@inheritDoc}
389    */
390   @Override
391   public float getMinimumScore(String type, boolean positional)
392   {
393     return featureStore.containsKey(type) ? featureStore.get(type)
394             .getMinimumScore(positional) : Float.NaN;
395   }
396
397   /**
398    * {@inheritDoc}
399    */
400   @Override
401   public float getMaximumScore(String type, boolean positional)
402   {
403     return featureStore.containsKey(type) ? featureStore.get(type)
404             .getMaximumScore(positional) : Float.NaN;
405   }
406
407   /**
408    * A convenience method to sort features by start position ascending (if on
409    * forward strand), or end position descending (if on reverse strand)
410    * 
411    * @param features
412    * @param forwardStrand
413    */
414   public static void sortFeatures(List<? extends IntervalI> features,
415           final boolean forwardStrand)
416   {
417     IntervalI.sortIntervals(features, forwardStrand);
418   }
419
420   /**
421    * {@inheritDoc} This method is 'semi-optimised': it only inspects features
422    * for types that include the specified group, but has to inspect every
423    * feature of those types for matching feature group. This is efficient unless
424    * a sequence has features that share the same type but are in different
425    * groups - an unlikely case.
426    * <p>
427    * For example, if RESNUM feature is created with group = PDBID, then features
428    * would only be retrieved for those sequences associated with the target
429    * PDBID (group).
430    */
431   @Override
432   public List<SequenceFeature> getFeaturesForGroup(boolean positional,
433           String group, String... type)
434   {
435     List<SequenceFeature> result = new ArrayList<>();
436     for (FeatureStore featureSet : varargToTypes(type))
437     {
438       if (featureSet.getFeatureGroups(positional).contains(group))
439       {
440         result.addAll(featureSet.getFeaturesForGroup(positional, group));
441       }
442     }
443     return result;
444   }
445
446   /**
447    * {@inheritDoc}
448    */
449   @Override
450   public boolean shiftFeatures(int fromPosition, int shiftBy)
451   {
452     boolean modified = false;
453     for (FeatureStore fs : featureStore.values())
454     {
455       modified |= fs.shiftFeatures(fromPosition, shiftBy);
456     }
457     return modified;
458   }
459
460   /**
461    * {@inheritDoc}
462    */
463   @Override
464   public void deleteAll()
465   {
466     featureStore.clear();
467   }
468 }