1 package jalview.datamodel.features;
3 import jalview.datamodel.ContiguousI;
4 import jalview.datamodel.SequenceFeature;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.Comparator;
9 import java.util.HashSet;
10 import java.util.List;
14 * A data store for a set of sequence features that supports efficient lookup of
15 * features overlapping a given range. Intended for (but not limited to) storage
16 * of features for one sequence and feature type.
21 public class FeatureStore
24 * a class providing criteria for performing a binary search of a list
26 abstract static class SearchCriterion
29 * Answers true if the entry passes the search criterion test
34 abstract boolean compare(SequenceFeature entry);
37 * serves a search condition for finding the first feature whose start
38 * position follows a given target location
43 static SearchCriterion byStart(final long target)
45 return new SearchCriterion() {
48 boolean compare(SequenceFeature entry)
50 return entry.getBegin() >= target;
56 * serves a search condition for finding the first feature whose end
57 * position is at or follows a given target location
62 static SearchCriterion byEnd(final long target)
64 return new SearchCriterion()
68 boolean compare(SequenceFeature entry)
70 return entry.getEnd() >= target;
76 * serves a search condition for finding the first feature which follows the
77 * given range as determined by a supplied comparator
82 static SearchCriterion byFeature(final ContiguousI to,
83 final Comparator<ContiguousI> rc)
85 return new SearchCriterion()
89 boolean compare(SequenceFeature entry)
91 return rc.compare(entry, to) >= 0;
98 * Non-positional features have no (zero) start/end position.
99 * Kept as a separate list in case this criterion changes in future.
101 List<SequenceFeature> nonPositionalFeatures;
104 * An ordered list of features, with the promise that no feature in the list
105 * properly contains any other. This constraint allows bounded linear search
106 * of the list for features overlapping a region.
107 * Contact features are not included in this list.
109 List<SequenceFeature> nonNestedFeatures;
112 * contact features ordered by first contact position
114 List<SequenceFeature> contactFeatureStarts;
117 * contact features ordered by second contact position
119 List<SequenceFeature> contactFeatureEnds;
122 * Nested Containment List is used to hold any features that are nested
123 * within (properly contained by) any other feature. This is a recursive tree
124 * which supports depth-first scan for features overlapping a range.
125 * It is used here as a 'catch-all' fallback for features that cannot be put
126 * into a simple ordered list without invalidating the search methods.
128 NCList<SequenceFeature> nestedFeatures;
131 * Feature groups represented in stored positional features
132 * (possibly including null)
134 Set<String> positionalFeatureGroups;
137 * Feature groups represented in stored non-positional features
138 * (possibly including null)
140 Set<String> nonPositionalFeatureGroups;
143 * the total length of all positional features; contact features count 1 to
144 * the total and 1 to size(), consistent with an average 'feature length' of 1
148 float positionalMinScore;
150 float positionalMaxScore;
152 float nonPositionalMinScore;
154 float nonPositionalMaxScore;
159 public FeatureStore()
161 nonNestedFeatures = new ArrayList<SequenceFeature>();
162 positionalFeatureGroups = new HashSet<String>();
163 nonPositionalFeatureGroups = new HashSet<String>();
164 positionalMinScore = Float.NaN;
165 positionalMaxScore = Float.NaN;
166 nonPositionalMinScore = Float.NaN;
167 nonPositionalMaxScore = Float.NaN;
169 // we only construct nonPositionalFeatures, contactFeatures
170 // or the NCList if we need to
174 * Adds one sequence feature to the store, and returns true, unless the
175 * feature is already contained in the store, in which case this method
176 * returns false. Containment is determined by SequenceFeature.equals()
181 public boolean addFeature(SequenceFeature feature)
183 if (contains(feature))
189 * keep a record of feature groups
191 if (!feature.isNonPositional())
193 positionalFeatureGroups.add(feature.getFeatureGroup());
196 boolean added = false;
198 if (feature.isContactFeature())
200 added = addContactFeature(feature);
202 else if (feature.isNonPositional())
204 added = addNonPositionalFeature(feature);
208 added = addNonNestedFeature(feature);
212 * detected a nested feature - put it in the NCList structure
214 added = addNestedFeature(feature);
221 * record the total extent of positional features, to make
222 * getTotalFeatureLength possible; we count the length of a
223 * contact feature as 1
225 totalExtent += getFeatureLength(feature);
228 * record the minimum and maximum score for positional
229 * and non-positional features
231 float score = feature.getScore();
232 if (!Float.isNaN(score))
234 if (feature.isNonPositional())
236 nonPositionalMinScore = min(nonPositionalMinScore, score);
237 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
241 positionalMinScore = min(positionalMinScore, score);
242 positionalMaxScore = max(positionalMaxScore, score);
251 * Answers true if this store contains the given feature (testing by
252 * SequenceFeature.equals), else false
257 public boolean contains(SequenceFeature feature)
259 if (feature.isNonPositional())
261 return nonPositionalFeatures == null ? false : nonPositionalFeatures
265 if (feature.isContactFeature())
267 return contactFeatureStarts == null ? false : listContains(
268 contactFeatureStarts, feature);
271 if (listContains(nonNestedFeatures, feature))
276 return nestedFeatures == null ? false : nestedFeatures
281 * Answers the 'length' of the feature, counting 0 for non-positional features
282 * and 1 for contact features
287 protected static int getFeatureLength(SequenceFeature feature)
289 if (feature.isNonPositional())
293 if (feature.isContactFeature())
297 return 1 + feature.getEnd() - feature.getBegin();
301 * Adds the feature to the list of non-positional features (with lazy
302 * instantiation of the list if it is null), and returns true. The feature
303 * group is added to the set of distinct feature groups for non-positional
304 * features. This method allows duplicate features, so test before calling to
309 protected boolean addNonPositionalFeature(SequenceFeature feature)
311 if (nonPositionalFeatures == null)
313 nonPositionalFeatures = new ArrayList<SequenceFeature>();
316 nonPositionalFeatures.add(feature);
318 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
324 * Adds one feature to the NCList that can manage nested features (creating
325 * the NCList if necessary), and returns true. If the feature is already
326 * stored in the NCList (by equality test), then it is not added, and this
327 * method returns false.
329 protected synchronized boolean addNestedFeature(SequenceFeature feature)
331 if (nestedFeatures == null)
333 nestedFeatures = new NCList<>(feature);
336 return nestedFeatures.add(feature, false);
340 * Add a feature to the list of non-nested features, maintaining the ordering
341 * of the list. A check is made for whether the feature is nested in (properly
342 * contained by) an existing feature. If there is no nesting, the feature is
343 * added to the list and the method returns true. If nesting is found, the
344 * feature is not added and the method returns false.
349 protected boolean addNonNestedFeature(SequenceFeature feature)
351 synchronized (nonNestedFeatures)
354 * find the first stored feature which doesn't precede the new one
356 int insertPosition = binarySearch(nonNestedFeatures,
357 SearchCriterion.byFeature(feature, RangeComparator.BY_START_POSITION));
360 * fail if we detect feature enclosure - of the new feature by
361 * the one preceding it, or of the next feature by the new one
363 if (insertPosition > 0)
365 if (encloses(nonNestedFeatures.get(insertPosition - 1), feature))
370 if (insertPosition < nonNestedFeatures.size())
372 if (encloses(feature, nonNestedFeatures.get(insertPosition)))
379 * checks passed - add the feature
381 nonNestedFeatures.add(insertPosition, feature);
388 * Answers true if range1 properly encloses range2, else false
394 protected boolean encloses(ContiguousI range1, ContiguousI range2)
396 int begin1 = range1.getBegin();
397 int begin2 = range2.getBegin();
398 int end1 = range1.getEnd();
399 int end2 = range2.getEnd();
400 if (begin1 == begin2 && end1 > end2)
404 if (begin1 < begin2 && end1 >= end2)
412 * Add a contact feature to the lists that hold them ordered by start (first
413 * contact) and by end (second contact) position, ensuring the lists remain
414 * ordered, and returns true. This method allows duplicate features to be
415 * added, so test before calling to avoid this.
420 protected synchronized boolean addContactFeature(SequenceFeature feature)
422 if (contactFeatureStarts == null)
424 contactFeatureStarts = new ArrayList<SequenceFeature>();
426 if (contactFeatureEnds == null)
428 contactFeatureEnds = new ArrayList<SequenceFeature>();
432 * binary search the sorted list to find the insertion point
434 int insertPosition = binarySearch(contactFeatureStarts,
435 SearchCriterion.byFeature(feature,
436 RangeComparator.BY_START_POSITION));
437 contactFeatureStarts.add(insertPosition, feature);
438 // and resort to mak siccar...just in case insertion point not quite right
439 Collections.sort(contactFeatureStarts, RangeComparator.BY_START_POSITION);
441 insertPosition = binarySearch(contactFeatureStarts,
442 SearchCriterion.byFeature(feature,
443 RangeComparator.BY_END_POSITION));
444 contactFeatureEnds.add(feature);
445 Collections.sort(contactFeatureEnds, RangeComparator.BY_END_POSITION);
451 * Answers true if the list contains the feature, else false. This method is
452 * optimised for the condition that the list is sorted on feature start
453 * position ascending, and will give unreliable results if this does not hold.
459 protected static boolean listContains(List<SequenceFeature> features,
460 SequenceFeature feature)
462 if (features == null || feature == null)
468 * locate the first entry in the list which does not precede the feature
470 int pos = binarySearch(features,
471 SearchCriterion.byFeature(feature, RangeComparator.BY_START_POSITION));
472 int len = features.size();
475 SequenceFeature sf = features.get(pos);
476 if (sf.getBegin() > feature.getBegin())
478 return false; // no match found
480 if (sf.equals(feature))
490 * Returns a (possibly empty) list of features whose extent overlaps the given
491 * range. The returned list is not ordered. Contact features are included if
492 * either of the contact points lies within the range.
495 * start position of overlap range (inclusive)
497 * end position of overlap range (inclusive)
500 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
502 List<SequenceFeature> result = new ArrayList<>();
504 findNonNestedFeatures(start, end, result);
506 findContactFeatures(start, end, result);
508 if (nestedFeatures != null)
510 result.addAll(nestedFeatures.findOverlaps(start, end));
517 * Adds contact features to the result list where either the second or the
518 * first contact position lies within the target range
524 protected void findContactFeatures(long from, long to,
525 List<SequenceFeature> result)
527 if (contactFeatureStarts != null)
529 findContactStartFeatures(from, to, result);
531 if (contactFeatureEnds != null)
533 findContactEndFeatures(from, to, result);
538 * Adds to the result list any contact features whose end (second contact
539 * point), but not start (first contact point), lies in the query from-to
546 protected void findContactEndFeatures(long from, long to,
547 List<SequenceFeature> result)
550 * find the first contact feature (if any) that does not lie
551 * entirely before the target range
553 int startPosition = binarySearch(contactFeatureEnds,
554 SearchCriterion.byEnd(from));
555 for (; startPosition < contactFeatureEnds.size(); startPosition++)
557 SequenceFeature sf = contactFeatureEnds.get(startPosition);
558 if (!sf.isContactFeature())
560 System.err.println("Error! non-contact feature type "
561 + sf.getType() + " in contact features list");
565 int begin = sf.getBegin();
566 if (begin >= from && begin <= to)
569 * this feature's first contact position lies in the search range
570 * so we don't include it in results a second time
575 int end = sf.getEnd();
576 if (end >= from && end <= to)
588 * Adds non-nested features to the result list that lie within the target
589 * range. Non-positional features (start=end=0), contact features and nested
590 * features are excluded.
596 protected void findNonNestedFeatures(long from, long to,
597 List<SequenceFeature> result)
600 * find the first feature whose end position is
601 * after the target range start
603 int startIndex = binarySearch(nonNestedFeatures,
604 SearchCriterion.byEnd(from));
606 final int startIndex1 = startIndex;
608 while (i < nonNestedFeatures.size())
610 SequenceFeature sf = nonNestedFeatures.get(i);
611 if (sf.getBegin() > to)
615 if (sf.getBegin() <= to && sf.getEnd() >= from)
624 * Adds contact features whose start position lies in the from-to range to the
631 protected void findContactStartFeatures(long from, long to,
632 List<SequenceFeature> result)
634 int startPosition = binarySearch(contactFeatureStarts,
635 SearchCriterion.byStart(from));
637 for (; startPosition < contactFeatureStarts.size(); startPosition++)
639 SequenceFeature sf = contactFeatureStarts.get(startPosition);
640 if (!sf.isContactFeature())
642 System.err.println("Error! non-contact feature type "
643 + sf.getType() + " in contact features list");
646 int begin = sf.getBegin();
647 if (begin >= from && begin <= to)
655 * Answers a list of all positional features stored, in no guaranteed order
659 public List<SequenceFeature> getPositionalFeatures()
662 * add non-nested features (may be all features for many cases)
664 List<SequenceFeature> result = new ArrayList<>();
665 result.addAll(nonNestedFeatures);
668 * add any contact features - from the list by start position
670 if (contactFeatureStarts != null)
672 result.addAll(contactFeatureStarts);
676 * add any nested features
678 if (nestedFeatures != null)
680 result.addAll(nestedFeatures.getEntries());
687 * Answers a list of all contact features. If there are none, returns an
688 * immutable empty list.
692 public List<SequenceFeature> getContactFeatures()
694 if (contactFeatureStarts == null)
696 return Collections.emptyList();
698 return new ArrayList<>(contactFeatureStarts);
702 * Answers a list of all non-positional features. If there are none, returns
703 * an immutable empty list.
707 public List<SequenceFeature> getNonPositionalFeatures()
709 if (nonPositionalFeatures == null)
711 return Collections.emptyList();
713 return new ArrayList<>(nonPositionalFeatures);
717 * Deletes the given feature from the store, returning true if it was found
718 * (and deleted), else false. This method makes no assumption that the feature
719 * is in the 'expected' place in the store, in case it has been modified since
724 public synchronized boolean delete(SequenceFeature sf)
727 * try the non-nested positional features first
729 boolean removed = nonNestedFeatures.remove(sf);
732 * if not found, try contact positions (and if found, delete
733 * from both lists of contact positions)
735 if (!removed && contactFeatureStarts != null)
737 removed = contactFeatureStarts.remove(sf);
740 contactFeatureEnds.remove(sf);
744 boolean removedNonPositional = false;
747 * if not found, try non-positional features
749 if (!removed && nonPositionalFeatures != null)
751 removedNonPositional = nonPositionalFeatures.remove(sf);
752 removed = removedNonPositional;
756 * if not found, try nested features
758 if (!removed && nestedFeatures != null)
760 removed = nestedFeatures.delete(sf);
772 * Rescan all features to recompute any cached values after an entry has been
773 * deleted. This is expected to be an infrequent event, so performance here is
776 protected synchronized void rescanAfterDelete()
778 positionalFeatureGroups.clear();
779 nonPositionalFeatureGroups.clear();
781 positionalMinScore = Float.NaN;
782 positionalMaxScore = Float.NaN;
783 nonPositionalMinScore = Float.NaN;
784 nonPositionalMaxScore = Float.NaN;
787 * scan non-positional features for groups and scores
789 for (SequenceFeature sf : getNonPositionalFeatures())
791 nonPositionalFeatureGroups.add(sf.getFeatureGroup());
792 float score = sf.getScore();
793 nonPositionalMinScore = min(nonPositionalMinScore, score);
794 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
798 * scan positional features for groups, scores and extents
800 for (SequenceFeature sf : getPositionalFeatures())
802 positionalFeatureGroups.add(sf.getFeatureGroup());
803 float score = sf.getScore();
804 positionalMinScore = min(positionalMinScore, score);
805 positionalMaxScore = max(positionalMaxScore, score);
806 totalExtent += getFeatureLength(sf);
811 * A helper method to return the minimum of two floats, where a non-NaN value
812 * is treated as 'less than' a NaN value (unlike Math.min which does the
818 protected static float min(float f1, float f2)
822 return Float.isNaN(f2) ? f1 : f2;
826 return Float.isNaN(f2) ? f1 : Math.min(f1, f2);
831 * A helper method to return the maximum of two floats, where a non-NaN value
832 * is treated as 'greater than' a NaN value (unlike Math.max which does the
838 protected static float max(float f1, float f2)
842 return Float.isNaN(f2) ? f1 : f2;
846 return Float.isNaN(f2) ? f1 : Math.max(f1, f2);
851 * Answers true if this store has no features, else false
855 public boolean isEmpty()
857 boolean hasFeatures = !nonNestedFeatures.isEmpty()
858 || (contactFeatureStarts != null && !contactFeatureStarts
860 || (nonPositionalFeatures != null && !nonPositionalFeatures
862 || (nestedFeatures != null && nestedFeatures.size() > 0);
868 * Answers the set of distinct feature groups stored, possibly including null,
869 * as an unmodifiable view of the set. The parameter determines whether the
870 * groups for positional or for non-positional features are returned.
872 * @param positionalFeatures
875 public Set<String> getFeatureGroups(boolean positionalFeatures)
877 if (positionalFeatures)
879 return Collections.unmodifiableSet(positionalFeatureGroups);
883 return nonPositionalFeatureGroups == null ? Collections
884 .<String> emptySet() : Collections
885 .unmodifiableSet(nonPositionalFeatureGroups);
890 * Performs a binary search of the (sorted) list to find the index of the
891 * first entry which returns true for the given comparator function. Returns
892 * the length of the list if there is no such entry.
898 protected static int binarySearch(List<SequenceFeature> features,
902 int end = features.size() - 1;
903 int matched = features.size();
907 int mid = (start + end) / 2;
908 SequenceFeature entry = features.get(mid);
909 boolean compare = sc.compare(entry);
925 * Answers the number of positional (or non-positional) features stored.
926 * Contact features count as 1.
931 public int getFeatureCount(boolean positional)
935 return nonPositionalFeatures == null ? 0 : nonPositionalFeatures
939 int size = nonNestedFeatures.size();
941 if (contactFeatureStarts != null)
943 // note a contact feature (start/end) counts as one
944 size += contactFeatureStarts.size();
947 if (nestedFeatures != null)
949 size += nestedFeatures.size();
956 * Answers the total length of positional features (or zero if there are
957 * none). Contact features contribute a value of 1 to the total.
961 public int getTotalFeatureLength()
967 * Answers the minimum score held for positional or non-positional features.
968 * This may be Float.NaN if there are no features, are none has a non-NaN
974 public float getMinimumScore(boolean positional)
976 return positional ? positionalMinScore : nonPositionalMinScore;
980 * Answers the maximum score held for positional or non-positional features.
981 * This may be Float.NaN if there are no features, are none has a non-NaN
987 public float getMaximumScore(boolean positional)
989 return positional ? positionalMaxScore : nonPositionalMaxScore;
993 * Answers a list of all either positional or non-positional features whose
994 * feature group matches the given group (which may be null)
1000 public List<SequenceFeature> getFeaturesForGroup(boolean positional,
1003 List<SequenceFeature> result = new ArrayList<>();
1006 * if we know features don't include the target group, no need
1007 * to inspect them for matches
1009 if (positional && !positionalFeatureGroups.contains(group)
1010 || !positional && !nonPositionalFeatureGroups.contains(group))
1015 List<SequenceFeature> sfs = positional ? getPositionalFeatures()
1016 : getNonPositionalFeatures();
1017 for (SequenceFeature sf : sfs)
1019 String featureGroup = sf.getFeatureGroup();
1020 if (group == null && featureGroup == null || group != null
1021 && group.equals(featureGroup))
1030 * Adds the shift value to the start and end of all positional features.
1031 * Returns true if at least one feature was updated, else false.
1036 public synchronized boolean shiftFeatures(int shift)
1039 * Because begin and end are final fields (to ensure the data store's
1040 * integrity), we have to delete each feature and re-add it as amended.
1041 * (Although a simple shift of all values would preserve data integrity!)
1043 boolean modified = false;
1044 for (SequenceFeature sf : getPositionalFeatures())
1047 int newBegin = sf.getBegin() + shift;
1048 int newEnd = sf.getEnd() + shift;
1051 * sanity check: don't shift left of the first residue
1055 newBegin = Math.max(1, newBegin);
1056 SequenceFeature sf2 = new SequenceFeature(sf, newBegin, newEnd,
1057 sf.getFeatureGroup(), sf.getScore());