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 * getAverageFeatureLength possible; we count the length of a
188 * contact feature as 1
190 if (added && !feature.isNonPositional())
192 int featureLength = feature.isContactFeature() ? 1 : 1
193 + feature.getEnd() - feature.getBegin();
194 totalExtent += featureLength;
201 * Adds the feature to the list of non-positional features (with lazy
202 * instantiation of the list if it is null), and returns true. If the
203 * non-positional features already include the new feature (by equality test),
204 * then it is not added, and this method returns false. The feature group is
205 * added to the set of distinct feature groups for non-positional features.
209 protected boolean addNonPositionalFeature(SequenceFeature feature)
211 if (nonPositionalFeatures == null)
213 nonPositionalFeatures = new ArrayList<SequenceFeature>();
214 nonPositionalFeatureGroups = new HashSet<String>();
216 if (nonPositionalFeatures.contains(feature))
221 nonPositionalFeatures.add(feature);
223 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
229 * Adds one feature to the NCList that can manage nested features (creating
230 * the NCList if necessary), and returns true. If the feature is already
231 * stored in the NCList (by equality test), then it is not added, and this
232 * method returns false.
234 protected synchronized boolean addNestedFeature(SequenceFeature feature)
236 if (nestedFeatures == null)
238 nestedFeatures = new NCList<SequenceFeature>(feature);
241 return nestedFeatures.add(feature, false);
245 * Add a feature to the list of non-nested features, maintaining the ordering
246 * of the list. A check is made for whether the feature is nested in (properly
247 * contained by) an existing feature. If there is no nesting, the feature is
248 * added to the list and the method returns true. If nesting is found, the
249 * feature is not added and the method returns false.
254 protected boolean addNonNestedFeature(SequenceFeature feature)
256 synchronized (nonNestedFeatures)
259 * find the first stored feature which doesn't precede the new one
261 int insertPosition = binarySearch(nonNestedFeatures,
262 SearchCriterion.byFeature(feature, startOrdering));
265 * fail if we detect feature enclosure - of the new feature by
266 * the one preceding it, or of the next feature by the new one
268 if (insertPosition > 0)
270 if (encloses(nonNestedFeatures.get(insertPosition - 1), feature))
275 if (insertPosition < nonNestedFeatures.size())
277 if (encloses(feature, nonNestedFeatures.get(insertPosition)))
284 * checks passed - add the feature
286 nonNestedFeatures.add(insertPosition, feature);
293 * Answers true if range1 properly encloses range2, else false
299 protected boolean encloses(ContiguousI range1, ContiguousI range2)
301 int begin1 = range1.getBegin();
302 int begin2 = range2.getBegin();
303 int end1 = range1.getEnd();
304 int end2 = range2.getEnd();
305 if (begin1 == begin2 && end1 > end2)
309 if (begin1 < begin2 && end1 >= end2)
317 * Add a contact feature to the lists that hold them ordered by start (first
318 * contact) and by end (second contact) position, ensuring the lists remain
319 * ordered, and returns true. If the contact feature lists already contain the
320 * given feature (by test for equality), does not add it and returns false.
325 protected synchronized boolean addContactFeature(SequenceFeature feature)
327 if (contactFeatureStarts == null)
329 contactFeatureStarts = new ArrayList<SequenceFeature>();
331 if (contactFeatureEnds == null)
333 contactFeatureEnds = new ArrayList<SequenceFeature>();
336 // TODO binary search for insertion points!
337 if (contactFeatureStarts.contains(feature))
342 contactFeatureStarts.add(feature);
343 Collections.sort(contactFeatureStarts, startOrdering);
344 contactFeatureEnds.add(feature);
345 Collections.sort(contactFeatureEnds, endOrdering);
351 * Returns a (possibly empty) list of features whose extent overlaps the given
352 * range. The returned list is not ordered. Contact features are included if
353 * either of the contact points lies within the range.
356 * start position of overlap range (inclusive)
358 * end position of overlap range (inclusive)
361 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
363 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
365 findNonNestedFeatures(start, end, result);
367 findContactFeatures(start, end, result);
369 if (nestedFeatures != null)
371 result.addAll(nestedFeatures.findOverlaps(start, end));
378 * Adds contact features to the result list where either the second or the
379 * first contact position lies within the target range
385 protected void findContactFeatures(long from, long to,
386 List<SequenceFeature> result)
388 if (contactFeatureStarts != null)
390 findContactStartFeatures(from, to, result);
392 if (contactFeatureEnds != null)
394 findContactEndFeatures(from, to, result);
399 * Adds to the result list any contact features whose end (second contact
400 * point), but not start (first contact point), lies in the query from-to
407 protected void findContactEndFeatures(long from, long to,
408 List<SequenceFeature> result)
411 * find the first contact feature (if any) that does not lie
412 * entirely before the target range
414 int startPosition = binarySearch(contactFeatureEnds,
415 SearchCriterion.byEnd(from));
416 for (; startPosition < contactFeatureEnds.size(); startPosition++)
418 SequenceFeature sf = contactFeatureEnds.get(startPosition);
419 if (!sf.isContactFeature())
421 System.err.println("Error! non-contact feature type "
422 + sf.getType() + " in contact features list");
426 int begin = sf.getBegin();
427 if (begin >= from && begin <= to)
430 * this feature's first contact position lies in the search range
431 * so we don't include it in results a second time
436 int end = sf.getEnd();
437 if (end >= from && end <= to)
449 * Adds non-nested features to the result list that lie within the target
450 * range. Non-positional features (start=end=0), contact features and nested
451 * features are excluded.
457 protected void findNonNestedFeatures(long from, long to,
458 List<SequenceFeature> result)
460 int startIndex = binarySearch(nonNestedFeatures,
461 SearchCriterion.byEnd(from));
463 findNonNestedFeatures(startIndex, from, to, result);
467 * Scans the list of non-nested features, starting from startIndex, to find
468 * those that overlap the from-to range, and adds them to the result list.
469 * Returns the index of the first feature whose start position is after the
470 * target range (or the length of the whole list if none such feature exists).
478 protected int findNonNestedFeatures(final int startIndex, long from,
479 long to, List<SequenceFeature> result)
482 while (i < nonNestedFeatures.size())
484 SequenceFeature sf = nonNestedFeatures.get(i);
485 if (sf.getBegin() > to)
489 int start = sf.getBegin();
490 int end = sf.getEnd();
491 if (start <= to && end >= from)
501 * Adds contact features whose start position lies in the from-to range to the
508 protected void findContactStartFeatures(long from, long to,
509 List<SequenceFeature> result)
511 int startPosition = binarySearch(contactFeatureStarts,
512 SearchCriterion.byStart(from));
514 for (; startPosition < contactFeatureStarts.size(); startPosition++)
516 SequenceFeature sf = contactFeatureStarts.get(startPosition);
517 if (!sf.isContactFeature())
519 System.err.println("Error! non-contact feature type "
520 + sf.getType() + " in contact features list");
523 int begin = sf.getBegin();
524 if (begin >= from && begin <= to)
532 * Answers a list of all positional features stored, in no guaranteed order
536 public List<SequenceFeature> getPositionalFeatures()
539 * add non-nested features (may be all features for many cases)
541 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
542 result.addAll(nonNestedFeatures);
545 * add any contact features - from the list by start position
547 if (contactFeatureStarts != null)
549 result.addAll(contactFeatureStarts);
553 * add any nested features
555 if (nestedFeatures != null)
557 result.addAll(nestedFeatures.getEntries());
564 * Answers a list of all contact features. If there are none, returns an
565 * immutable empty list.
569 public List<SequenceFeature> getContactFeatures()
571 if (contactFeatureStarts == null)
573 return Collections.emptyList();
575 return new ArrayList<SequenceFeature>(contactFeatureStarts);
579 * Answers a list of all non-positional features. If there are none, returns
580 * an immutable empty list.
584 public List<SequenceFeature> getNonPositionalFeatures()
586 if (nonPositionalFeatures == null)
588 return Collections.emptyList();
590 return new ArrayList<SequenceFeature>(nonPositionalFeatures);
594 * Deletes the given feature from the store, returning true if it was found
595 * (and deleted), else false. This method makes no assumption that the feature
596 * is in the 'expected' place in the store, in case it has been modified since
601 public synchronized boolean delete(SequenceFeature sf)
604 * try the non-nested positional features first
606 boolean removed = nonNestedFeatures.remove(sf);
609 * if not found, try contact positions (and if found, delete
610 * from both lists of contact positions)
612 if (!removed && contactFeatureStarts != null)
614 removed = contactFeatureStarts.remove(sf);
617 contactFeatureEnds.remove(sf);
621 boolean removedNonPositional = false;
624 * if not found, try non-positional features
626 if (!removed && nonPositionalFeatures != null)
628 removedNonPositional = nonPositionalFeatures.remove(sf);
629 removed = removedNonPositional;
633 * if not found, try nested features
635 if (!removed && nestedFeatures != null)
637 removed = nestedFeatures.delete(sf);
642 rebuildFeatureGroups(sf.getFeatureGroup(), removedNonPositional);
643 // TODO and recalculate totalExtent (feature may have changed length!)
650 * Check whether the given feature group is still represented, in either
651 * positional or non-positional features, and if not, remove it from the set
654 * @param featureGroup
655 * @param nonPositional
657 protected void rebuildFeatureGroups(String featureGroup,
658 boolean nonPositional)
660 if (nonPositional && nonPositionalFeatures != null)
662 boolean found = false;
663 for (SequenceFeature sf : nonPositionalFeatures)
665 String group = sf.getFeatureGroup();
666 if (featureGroup == group
667 || (featureGroup != null && featureGroup.equals(group)))
675 nonPositionalFeatureGroups.remove(featureGroup);
678 else if (!findFeatureGroup(featureGroup))
680 positionalFeatureGroups.remove(featureGroup);
685 * Scans all positional features to check whether the given feature group is
686 * found, and returns true if found, else false
688 * @param featureGroup
691 protected boolean findFeatureGroup(String featureGroup)
693 for (SequenceFeature sf : getPositionalFeatures())
695 String group = sf.getFeatureGroup();
696 if (group == featureGroup
697 || (group != null && group.equals(featureGroup)))
706 * Answers true if this store has no features, else false
710 public boolean isEmpty()
712 boolean hasFeatures = !nonNestedFeatures.isEmpty()
713 || (contactFeatureStarts != null && !contactFeatureStarts
715 || (nonPositionalFeatures != null && !nonPositionalFeatures
717 || (nestedFeatures != null && nestedFeatures.size() > 0);
723 * Answers the set of distinct feature groups stored, possibly including null,
724 * as an unmodifiable view of the set. The parameter determines whether the
725 * groups for positional or for non-positional features are returned.
727 * @param positionalFeatures
730 public Set<String> getFeatureGroups(boolean positionalFeatures)
732 if (positionalFeatures)
734 return Collections.unmodifiableSet(positionalFeatureGroups);
738 return nonPositionalFeatureGroups == null ? Collections
739 .<String> emptySet() : Collections
740 .unmodifiableSet(nonPositionalFeatureGroups);
745 * Performs a binary search of the (sorted) list to find the index of the
746 * first entry which returns true for the given comparator function. Returns
747 * the length of the list if there is no such entry.
753 protected int binarySearch(List<SequenceFeature> features,
757 int end = features.size() - 1;
758 int matched = features.size();
762 int mid = (start + end) / 2;
763 SequenceFeature entry = features.get(mid);
764 boolean compare = sc.compare(entry);
780 * Answers the number of positional (or non-positional) features stored
785 public int size(boolean positional)
789 return nonPositionalFeatures == null ? 0 : nonPositionalFeatures
793 int size = nonNestedFeatures.size();
795 if (contactFeatureStarts != null)
797 // note a contact feature (start/end) counts as one
798 size += contactFeatureStarts.size();
801 if (nestedFeatures != null)
803 size += nestedFeatures.size();
810 * Answers the average length of positional features (or zero if there are
811 * none). Contact features contribute a value of 1 to the average.
815 public float getAverageFeatureLength()
818 return d == 0 ? 0f : (float) totalExtent / d;