1 package jalview.datamodel.features;
3 import jalview.datamodel.SequenceFeature;
5 import java.util.ArrayList;
6 import java.util.Collections;
7 import java.util.Comparator;
8 import java.util.HashSet;
13 * A data store for a set of sequence features that supports efficient lookup of
14 * features overlapping a given range. Intended for (but not limited to) storage
15 * of features for one sequence and feature type.
20 public class FeatureStore
23 * a class providing criteria for performing a binary search of a list
25 abstract static class SearchCriterion
28 * Answers true if the entry passes the search criterion test
33 abstract boolean compare(SequenceFeature entry);
35 static SearchCriterion byStart(final long target)
37 return new SearchCriterion() {
40 boolean compare(SequenceFeature entry)
42 return entry.getBegin() >= target;
47 static SearchCriterion byEnd(final long target)
49 return new SearchCriterion()
53 boolean compare(SequenceFeature entry)
55 return entry.getEnd() >= target;
60 static SearchCriterion byFeature(final ContiguousI to,
61 final Comparator<ContiguousI> rc)
63 return new SearchCriterion()
67 boolean compare(SequenceFeature entry)
69 return rc.compare(entry, to) >= 0;
75 Comparator<ContiguousI> startOrdering = new RangeComparator(true);
77 Comparator<ContiguousI> endOrdering = new RangeComparator(false);
80 * Non-positional features have no (zero) start/end position.
81 * Kept as a separate list in case this criterion changes in future.
83 List<SequenceFeature> nonPositionalFeatures;
86 * An ordered list of features, with the promise that no feature in the list
87 * properly contains any other. This constraint allows bounded linear search
88 * of the list for features overlapping a region.
89 * Contact features are not included in this list.
91 List<SequenceFeature> nonNestedFeatures;
94 * contact features ordered by first contact position
96 List<SequenceFeature> contactFeatureStarts;
99 * contact features ordered by second contact position
101 List<SequenceFeature> contactFeatureEnds;
104 * Nested Containment List is used to hold any features that are nested
105 * within (properly contained by) any other feature. This is a recursive tree
106 * which supports depth-first scan for features overlapping a range.
107 * It is used here as a 'catch-all' fallback for features that cannot be put
108 * into a simple ordered list without invalidating the search methods.
110 NCList<SequenceFeature> nestedFeatures;
113 * Feature groups represented in stored positional features
114 * (possibly including null)
116 Set<String> positionalFeatureGroups;
119 * Feature groups represented in stored non-positional features
120 * (possibly including null)
122 Set<String> nonPositionalFeatureGroups;
125 * the total length of all positional features; contact features count 1 to
126 * the total and 1 to size(), consistent with an average 'feature length' of 1
133 public FeatureStore()
135 nonNestedFeatures = new ArrayList<SequenceFeature>();
136 positionalFeatureGroups = new HashSet<String>();
138 // we only construct nonPositionalFeatures, contactFeatures
139 // or the NCList if we need to
143 * Adds one sequence feature to the store, and returns true, unless the
144 * feature is already contained in the store, in which case this method
145 * returns false. Containment is determined by SequenceFeature.equals()
150 public boolean addFeature(SequenceFeature feature)
153 * keep a record of feature groups
155 if (!feature.isNonPositional())
157 positionalFeatureGroups.add(feature.getFeatureGroup());
160 boolean added = false;
162 if (feature.isContactFeature())
164 added = addContactFeature(feature);
166 else if (feature.isNonPositional())
168 added = addNonPositionalFeature(feature);
172 if (!nonNestedFeatures.contains(feature))
174 added = addNonNestedFeature(feature);
178 * detected a nested feature - put it in the NCList structure
180 added = addNestedFeature(feature);
186 * record the total extent of positional features, to make
187 * getTotalFeatureLength possible; we count the length of a
188 * contact feature as 1
192 totalExtent += getFeatureLength(feature);
199 * Answers the 'length' of the feature, counting 0 for non-positional features
200 * and 1 for contact features
205 protected static int getFeatureLength(SequenceFeature feature)
207 if (feature.isNonPositional())
211 if (feature.isContactFeature())
215 return 1 + feature.getEnd() - feature.getBegin();
219 * Adds the feature to the list of non-positional features (with lazy
220 * instantiation of the list if it is null), and returns true. If the
221 * non-positional features already include the new feature (by equality test),
222 * then it is not added, and this method returns false. The feature group is
223 * added to the set of distinct feature groups for non-positional features.
227 protected boolean addNonPositionalFeature(SequenceFeature feature)
229 if (nonPositionalFeatures == null)
231 nonPositionalFeatures = new ArrayList<SequenceFeature>();
232 nonPositionalFeatureGroups = new HashSet<String>();
234 if (nonPositionalFeatures.contains(feature))
239 nonPositionalFeatures.add(feature);
241 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
247 * Adds one feature to the NCList that can manage nested features (creating
248 * the NCList if necessary), and returns true. If the feature is already
249 * stored in the NCList (by equality test), then it is not added, and this
250 * method returns false.
252 protected synchronized boolean addNestedFeature(SequenceFeature feature)
254 if (nestedFeatures == null)
256 nestedFeatures = new NCList<SequenceFeature>(feature);
259 return nestedFeatures.add(feature, false);
263 * Add a feature to the list of non-nested features, maintaining the ordering
264 * of the list. A check is made for whether the feature is nested in (properly
265 * contained by) an existing feature. If there is no nesting, the feature is
266 * added to the list and the method returns true. If nesting is found, the
267 * feature is not added and the method returns false.
272 protected boolean addNonNestedFeature(SequenceFeature feature)
274 synchronized (nonNestedFeatures)
277 * find the first stored feature which doesn't precede the new one
279 int insertPosition = binarySearch(nonNestedFeatures,
280 SearchCriterion.byFeature(feature, startOrdering));
283 * fail if we detect feature enclosure - of the new feature by
284 * the one preceding it, or of the next feature by the new one
286 if (insertPosition > 0)
288 if (encloses(nonNestedFeatures.get(insertPosition - 1), feature))
293 if (insertPosition < nonNestedFeatures.size())
295 if (encloses(feature, nonNestedFeatures.get(insertPosition)))
302 * checks passed - add the feature
304 nonNestedFeatures.add(insertPosition, feature);
311 * Answers true if range1 properly encloses range2, else false
317 protected boolean encloses(ContiguousI range1, ContiguousI range2)
319 int begin1 = range1.getBegin();
320 int begin2 = range2.getBegin();
321 int end1 = range1.getEnd();
322 int end2 = range2.getEnd();
323 if (begin1 == begin2 && end1 > end2)
327 if (begin1 < begin2 && end1 >= end2)
335 * Add a contact feature to the lists that hold them ordered by start (first
336 * contact) and by end (second contact) position, ensuring the lists remain
337 * ordered, and returns true. If the contact feature lists already contain the
338 * given feature (by test for equality), does not add it and returns false.
343 protected synchronized boolean addContactFeature(SequenceFeature feature)
345 if (contactFeatureStarts == null)
347 contactFeatureStarts = new ArrayList<SequenceFeature>();
349 if (contactFeatureEnds == null)
351 contactFeatureEnds = new ArrayList<SequenceFeature>();
354 // TODO binary search for insertion points!
355 if (contactFeatureStarts.contains(feature))
360 contactFeatureStarts.add(feature);
361 Collections.sort(contactFeatureStarts, startOrdering);
362 contactFeatureEnds.add(feature);
363 Collections.sort(contactFeatureEnds, endOrdering);
369 * Returns a (possibly empty) list of features whose extent overlaps the given
370 * range. The returned list is not ordered. Contact features are included if
371 * either of the contact points lies within the range.
374 * start position of overlap range (inclusive)
376 * end position of overlap range (inclusive)
379 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
381 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
383 findNonNestedFeatures(start, end, result);
385 findContactFeatures(start, end, result);
387 if (nestedFeatures != null)
389 result.addAll(nestedFeatures.findOverlaps(start, end));
396 * Adds contact features to the result list where either the second or the
397 * first contact position lies within the target range
403 protected void findContactFeatures(long from, long to,
404 List<SequenceFeature> result)
406 if (contactFeatureStarts != null)
408 findContactStartFeatures(from, to, result);
410 if (contactFeatureEnds != null)
412 findContactEndFeatures(from, to, result);
417 * Adds to the result list any contact features whose end (second contact
418 * point), but not start (first contact point), lies in the query from-to
425 protected void findContactEndFeatures(long from, long to,
426 List<SequenceFeature> result)
429 * find the first contact feature (if any) that does not lie
430 * entirely before the target range
432 int startPosition = binarySearch(contactFeatureEnds,
433 SearchCriterion.byEnd(from));
434 for (; startPosition < contactFeatureEnds.size(); startPosition++)
436 SequenceFeature sf = contactFeatureEnds.get(startPosition);
437 if (!sf.isContactFeature())
439 System.err.println("Error! non-contact feature type "
440 + sf.getType() + " in contact features list");
444 int begin = sf.getBegin();
445 if (begin >= from && begin <= to)
448 * this feature's first contact position lies in the search range
449 * so we don't include it in results a second time
454 int end = sf.getEnd();
455 if (end >= from && end <= to)
467 * Adds non-nested features to the result list that lie within the target
468 * range. Non-positional features (start=end=0), contact features and nested
469 * features are excluded.
475 protected void findNonNestedFeatures(long from, long to,
476 List<SequenceFeature> result)
478 int startIndex = binarySearch(nonNestedFeatures,
479 SearchCriterion.byEnd(from));
481 findNonNestedFeatures(startIndex, from, to, result);
485 * Scans the list of non-nested features, starting from startIndex, to find
486 * those that overlap the from-to range, and adds them to the result list.
487 * Returns the index of the first feature whose start position is after the
488 * target range (or the length of the whole list if none such feature exists).
496 protected int findNonNestedFeatures(final int startIndex, long from,
497 long to, List<SequenceFeature> result)
500 while (i < nonNestedFeatures.size())
502 SequenceFeature sf = nonNestedFeatures.get(i);
503 if (sf.getBegin() > to)
507 int start = sf.getBegin();
508 int end = sf.getEnd();
509 if (start <= to && end >= from)
519 * Adds contact features whose start position lies in the from-to range to the
526 protected void findContactStartFeatures(long from, long to,
527 List<SequenceFeature> result)
529 int startPosition = binarySearch(contactFeatureStarts,
530 SearchCriterion.byStart(from));
532 for (; startPosition < contactFeatureStarts.size(); startPosition++)
534 SequenceFeature sf = contactFeatureStarts.get(startPosition);
535 if (!sf.isContactFeature())
537 System.err.println("Error! non-contact feature type "
538 + sf.getType() + " in contact features list");
541 int begin = sf.getBegin();
542 if (begin >= from && begin <= to)
550 * Answers a list of all positional features stored, in no guaranteed order
554 public List<SequenceFeature> getPositionalFeatures()
557 * add non-nested features (may be all features for many cases)
559 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
560 result.addAll(nonNestedFeatures);
563 * add any contact features - from the list by start position
565 if (contactFeatureStarts != null)
567 result.addAll(contactFeatureStarts);
571 * add any nested features
573 if (nestedFeatures != null)
575 result.addAll(nestedFeatures.getEntries());
582 * Answers a list of all contact features. If there are none, returns an
583 * immutable empty list.
587 public List<SequenceFeature> getContactFeatures()
589 if (contactFeatureStarts == null)
591 return Collections.emptyList();
593 return new ArrayList<SequenceFeature>(contactFeatureStarts);
597 * Answers a list of all non-positional features. If there are none, returns
598 * an immutable empty list.
602 public List<SequenceFeature> getNonPositionalFeatures()
604 if (nonPositionalFeatures == null)
606 return Collections.emptyList();
608 return new ArrayList<SequenceFeature>(nonPositionalFeatures);
612 * Deletes the given feature from the store, returning true if it was found
613 * (and deleted), else false. This method makes no assumption that the feature
614 * is in the 'expected' place in the store, in case it has been modified since
619 public synchronized boolean delete(SequenceFeature sf)
622 * try the non-nested positional features first
624 boolean removed = nonNestedFeatures.remove(sf);
627 * if not found, try contact positions (and if found, delete
628 * from both lists of contact positions)
630 if (!removed && contactFeatureStarts != null)
632 removed = contactFeatureStarts.remove(sf);
635 contactFeatureEnds.remove(sf);
639 boolean removedNonPositional = false;
642 * if not found, try non-positional features
644 if (!removed && nonPositionalFeatures != null)
646 removedNonPositional = nonPositionalFeatures.remove(sf);
647 removed = removedNonPositional;
651 * if not found, try nested features
653 if (!removed && nestedFeatures != null)
655 removed = nestedFeatures.delete(sf);
661 * rescan (positional or non-positional) features to rebuild the
662 * set of distinct feature groups present
664 rebuildFeatureGroups(sf.getFeatureGroup(), removedNonPositional);
667 * subtract deleted feature's length from stored total length
668 * TODO: can start/end have changed since the feature was added?
670 int extent = getFeatureLength(sf);
671 totalExtent = Math.max(0, totalExtent - extent);
678 * Check whether the given feature group is still represented, in either
679 * positional or non-positional features, and if not, remove it from the set
682 * @param featureGroup
683 * @param nonPositional
685 protected void rebuildFeatureGroups(String featureGroup,
686 boolean nonPositional)
688 if (nonPositional && nonPositionalFeatures != null)
690 boolean found = false;
691 for (SequenceFeature sf : nonPositionalFeatures)
693 String group = sf.getFeatureGroup();
694 if (featureGroup == group
695 || (featureGroup != null && featureGroup.equals(group)))
703 nonPositionalFeatureGroups.remove(featureGroup);
706 else if (!findFeatureGroup(featureGroup))
708 positionalFeatureGroups.remove(featureGroup);
713 * Scans all positional features to check whether the given feature group is
714 * found, and returns true if found, else false
716 * @param featureGroup
719 protected boolean findFeatureGroup(String featureGroup)
721 for (SequenceFeature sf : getPositionalFeatures())
723 String group = sf.getFeatureGroup();
724 if (group == featureGroup
725 || (group != null && group.equals(featureGroup)))
734 * Answers true if this store has no features, else false
738 public boolean isEmpty()
740 boolean hasFeatures = !nonNestedFeatures.isEmpty()
741 || (contactFeatureStarts != null && !contactFeatureStarts
743 || (nonPositionalFeatures != null && !nonPositionalFeatures
745 || (nestedFeatures != null && nestedFeatures.size() > 0);
751 * Answers the set of distinct feature groups stored, possibly including null,
752 * as an unmodifiable view of the set. The parameter determines whether the
753 * groups for positional or for non-positional features are returned.
755 * @param positionalFeatures
758 public Set<String> getFeatureGroups(boolean positionalFeatures)
760 if (positionalFeatures)
762 return Collections.unmodifiableSet(positionalFeatureGroups);
766 return nonPositionalFeatureGroups == null ? Collections
767 .<String> emptySet() : Collections
768 .unmodifiableSet(nonPositionalFeatureGroups);
773 * Performs a binary search of the (sorted) list to find the index of the
774 * first entry which returns true for the given comparator function. Returns
775 * the length of the list if there is no such entry.
781 protected int binarySearch(List<SequenceFeature> features,
785 int end = features.size() - 1;
786 int matched = features.size();
790 int mid = (start + end) / 2;
791 SequenceFeature entry = features.get(mid);
792 boolean compare = sc.compare(entry);
808 * Answers the number of positional (or non-positional) features stored.
809 * Contact features count as 1.
814 public int getFeatureCount(boolean positional)
818 return nonPositionalFeatures == null ? 0 : nonPositionalFeatures
822 int size = nonNestedFeatures.size();
824 if (contactFeatureStarts != null)
826 // note a contact feature (start/end) counts as one
827 size += contactFeatureStarts.size();
830 if (nestedFeatures != null)
832 size += nestedFeatures.size();
839 * Answers the total length of positional features (or zero if there are
840 * none). Contact features contribute a value of 1 to the total.
844 public int getTotalFeatureLength()