2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.datamodel.features;
23 import jalview.datamodel.SequenceFeature;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.List;
31 import intervalstore.api.IntervalStoreI;
32 import intervalstore.impl.BinarySearcher;
33 import intervalstore.impl.IntervalStore;
36 * A data store for a set of sequence features that supports efficient lookup of
37 * features overlapping a given range. Intended for (but not limited to) storage
38 * of features for one sequence and feature type.
43 public class FeatureStore
46 * Non-positional features have no (zero) start/end position.
47 * Kept as a separate list in case this criterion changes in future.
49 List<SequenceFeature> nonPositionalFeatures;
52 * contact features ordered by first contact position
54 List<SequenceFeature> contactFeatureStarts;
57 * contact features ordered by second contact position
59 List<SequenceFeature> contactFeatureEnds;
62 * IntervalStore holds remaining features and provides efficient
63 * query for features overlapping any given interval
65 IntervalStoreI<SequenceFeature> features;
68 * Feature groups represented in stored positional features
69 * (possibly including null)
71 Set<String> positionalFeatureGroups;
74 * Feature groups represented in stored non-positional features
75 * (possibly including null)
77 Set<String> nonPositionalFeatureGroups;
80 * the total length of all positional features; contact features count 1 to
81 * the total and 1 to size(), consistent with an average 'feature length' of 1
85 float positionalMinScore;
87 float positionalMaxScore;
89 float nonPositionalMinScore;
91 float nonPositionalMaxScore;
98 features = new IntervalStore<>();
99 positionalFeatureGroups = new HashSet<>();
100 nonPositionalFeatureGroups = new HashSet<>();
101 positionalMinScore = Float.NaN;
102 positionalMaxScore = Float.NaN;
103 nonPositionalMinScore = Float.NaN;
104 nonPositionalMaxScore = Float.NaN;
106 // we only construct nonPositionalFeatures, contactFeatures if we need to
110 * Adds one sequence feature to the store, and returns true, unless the
111 * feature is already contained in the store, in which case this method
112 * returns false. Containment is determined by SequenceFeature.equals()
117 public boolean addFeature(SequenceFeature feature)
119 if (contains(feature))
125 * keep a record of feature groups
127 if (!feature.isNonPositional())
129 positionalFeatureGroups.add(feature.getFeatureGroup());
132 if (feature.isContactFeature())
134 addContactFeature(feature);
136 else if (feature.isNonPositional())
138 addNonPositionalFeature(feature);
142 addNestedFeature(feature);
146 * record the total extent of positional features, to make
147 * getTotalFeatureLength possible; we count the length of a
148 * contact feature as 1
150 totalExtent += getFeatureLength(feature);
153 * record the minimum and maximum score for positional
154 * and non-positional features
156 float score = feature.getScore();
157 if (!Float.isNaN(score))
159 if (feature.isNonPositional())
161 nonPositionalMinScore = min(nonPositionalMinScore, score);
162 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
166 positionalMinScore = min(positionalMinScore, score);
167 positionalMaxScore = max(positionalMaxScore, score);
175 * Answers true if this store contains the given feature (testing by
176 * SequenceFeature.equals), else false
181 public boolean contains(SequenceFeature feature)
183 if (feature.isNonPositional())
185 return nonPositionalFeatures == null ? false : nonPositionalFeatures
189 if (feature.isContactFeature())
191 return contactFeatureStarts == null ? false : listContains(
192 contactFeatureStarts, feature);
195 return features == null ? false : features
200 * Answers the 'length' of the feature, counting 0 for non-positional features
201 * and 1 for contact features
206 protected static int getFeatureLength(SequenceFeature feature)
208 if (feature.isNonPositional())
212 if (feature.isContactFeature())
216 return 1 + feature.getEnd() - feature.getBegin();
220 * Adds the feature to the list of non-positional features (with lazy
221 * instantiation of the list if it is null), and returns true. The feature
222 * group is added to the set of distinct feature groups for non-positional
223 * features. This method allows duplicate features, so test before calling to
228 protected boolean addNonPositionalFeature(SequenceFeature feature)
230 if (nonPositionalFeatures == null)
232 nonPositionalFeatures = new ArrayList<>();
235 nonPositionalFeatures.add(feature);
237 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
243 * Adds one feature to the IntervalStore that can manage nested features
244 * (creating the IntervalStore if necessary)
246 protected synchronized void addNestedFeature(SequenceFeature feature)
248 if (features == null)
250 features = new IntervalStore<>();
252 features.add(feature);
256 * Add a contact feature to the lists that hold them ordered by start (first
257 * contact) and by end (second contact) position, ensuring the lists remain
258 * ordered, and returns true. This method allows duplicate features to be
259 * added, so test before calling to avoid this.
264 protected synchronized boolean addContactFeature(SequenceFeature feature)
266 if (contactFeatureStarts == null)
268 contactFeatureStarts = new ArrayList<>();
270 if (contactFeatureEnds == null)
272 contactFeatureEnds = new ArrayList<>();
276 * insert into list sorted by start (first contact position):
277 * binary search the sorted list to find the insertion point
279 int insertPosition = BinarySearcher.findFirst(contactFeatureStarts,
280 f -> f.getBegin() >= feature.getBegin());
281 contactFeatureStarts.add(insertPosition, feature);
285 * insert into list sorted by end (second contact position):
286 * binary search the sorted list to find the insertion point
288 insertPosition = BinarySearcher.findFirst(contactFeatureEnds,
289 f -> f.getEnd() >= feature.getEnd());
290 contactFeatureEnds.add(insertPosition, feature);
296 * Answers true if the list contains the feature, else false. This method is
297 * optimised for the condition that the list is sorted on feature start
298 * position ascending, and will give unreliable results if this does not hold.
304 protected static boolean listContains(List<SequenceFeature> features,
305 SequenceFeature feature)
307 if (features == null || feature == null)
313 * locate the first entry in the list which does not precede the feature
315 // int pos = binarySearch(features,
316 // SearchCriterion.byFeature(feature, RangeComparator.BY_START_POSITION));
317 int pos = BinarySearcher.findFirst(features,
318 val -> val.getBegin() >= feature.getBegin());
319 int len = features.size();
322 SequenceFeature sf = features.get(pos);
323 if (sf.getBegin() > feature.getBegin())
325 return false; // no match found
327 if (sf.equals(feature))
337 * Returns a (possibly empty) list of features whose extent overlaps the given
338 * range. The returned list is not ordered. Contact features are included if
339 * either of the contact points lies within the range.
342 * start position of overlap range (inclusive)
344 * end position of overlap range (inclusive)
347 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
349 List<SequenceFeature> result = new ArrayList<>();
351 findContactFeatures(start, end, result);
353 if (features != null)
355 result.addAll(features.findOverlaps(start, end));
362 * Adds contact features to the result list where either the second or the
363 * first contact position lies within the target range
369 protected void findContactFeatures(long from, long to,
370 List<SequenceFeature> result)
372 if (contactFeatureStarts != null)
374 findContactStartOverlaps(from, to, result);
376 if (contactFeatureEnds != null)
378 findContactEndOverlaps(from, to, result);
383 * Adds to the result list any contact features whose end (second contact
384 * point), but not start (first contact point), lies in the query from-to
391 protected void findContactEndOverlaps(long from, long to,
392 List<SequenceFeature> result)
395 * find the first contact feature (if any)
396 * whose end point is not before the target range
398 int index = BinarySearcher.findFirst(contactFeatureEnds,
399 f -> f.getEnd() >= from);
401 while (index < contactFeatureEnds.size())
403 SequenceFeature sf = contactFeatureEnds.get(index);
404 if (!sf.isContactFeature())
406 System.err.println("Error! non-contact feature type "
407 + sf.getType() + " in contact features list");
412 int begin = sf.getBegin();
413 if (begin >= from && begin <= to)
416 * this feature's first contact position lies in the search range
417 * so we don't include it in results a second time
423 if (sf.getEnd() > to)
426 * this feature (and all following) has end point after the target range
432 * feature has end >= from and end <= to
433 * i.e. contact end point lies within overlap search range
441 * Adds contact features whose start position lies in the from-to range to the
448 protected void findContactStartOverlaps(long from, long to,
449 List<SequenceFeature> result)
451 int index = BinarySearcher.findFirst(contactFeatureStarts,
452 f -> f.getBegin() >= from);
454 while (index < contactFeatureStarts.size())
456 SequenceFeature sf = contactFeatureStarts.get(index);
457 if (!sf.isContactFeature())
459 System.err.println("Error! non-contact feature " + sf.toString()
460 + " in contact features list");
464 if (sf.getBegin() > to)
467 * this feature's start (and all following) follows the target range
473 * feature has begin >= from and begin <= to
474 * i.e. contact start point lies within overlap search range
482 * Answers a list of all positional features stored, in no guaranteed order
486 public List<SequenceFeature> getPositionalFeatures()
488 List<SequenceFeature> result = new ArrayList<>();
491 * add any contact features - from the list by start position
493 if (contactFeatureStarts != null)
495 result.addAll(contactFeatureStarts);
499 * add any nested features
501 if (features != null)
503 result.addAll(features);
510 * Answers a list of all contact features. If there are none, returns an
511 * immutable empty list.
515 public List<SequenceFeature> getContactFeatures()
517 if (contactFeatureStarts == null)
519 return Collections.emptyList();
521 return new ArrayList<>(contactFeatureStarts);
525 * Answers a list of all non-positional features. If there are none, returns
526 * an immutable empty list.
530 public List<SequenceFeature> getNonPositionalFeatures()
532 if (nonPositionalFeatures == null)
534 return Collections.emptyList();
536 return new ArrayList<>(nonPositionalFeatures);
540 * Deletes the given feature from the store, returning true if it was found
541 * (and deleted), else false. This method makes no assumption that the feature
542 * is in the 'expected' place in the store, in case it has been modified since
547 public synchronized boolean delete(SequenceFeature sf)
549 boolean removed = false;
552 * try contact positions (and if found, delete
553 * from both lists of contact positions)
555 if (!removed && contactFeatureStarts != null)
557 removed = contactFeatureStarts.remove(sf);
560 contactFeatureEnds.remove(sf);
564 boolean removedNonPositional = false;
567 * if not found, try non-positional features
569 if (!removed && nonPositionalFeatures != null)
571 removedNonPositional = nonPositionalFeatures.remove(sf);
572 removed = removedNonPositional;
576 * if not found, try nested features
578 if (!removed && features != null)
580 removed = features.remove(sf);
592 * Rescan all features to recompute any cached values after an entry has been
593 * deleted. This is expected to be an infrequent event, so performance here is
596 protected synchronized void rescanAfterDelete()
598 positionalFeatureGroups.clear();
599 nonPositionalFeatureGroups.clear();
601 positionalMinScore = Float.NaN;
602 positionalMaxScore = Float.NaN;
603 nonPositionalMinScore = Float.NaN;
604 nonPositionalMaxScore = Float.NaN;
607 * scan non-positional features for groups and scores
609 for (SequenceFeature sf : getNonPositionalFeatures())
611 nonPositionalFeatureGroups.add(sf.getFeatureGroup());
612 float score = sf.getScore();
613 nonPositionalMinScore = min(nonPositionalMinScore, score);
614 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
618 * scan positional features for groups, scores and extents
620 for (SequenceFeature sf : getPositionalFeatures())
622 positionalFeatureGroups.add(sf.getFeatureGroup());
623 float score = sf.getScore();
624 positionalMinScore = min(positionalMinScore, score);
625 positionalMaxScore = max(positionalMaxScore, score);
626 totalExtent += getFeatureLength(sf);
631 * A helper method to return the minimum of two floats, where a non-NaN value
632 * is treated as 'less than' a NaN value (unlike Math.min which does the
638 protected static float min(float f1, float f2)
642 return Float.isNaN(f2) ? f1 : f2;
646 return Float.isNaN(f2) ? f1 : Math.min(f1, f2);
651 * A helper method to return the maximum of two floats, where a non-NaN value
652 * is treated as 'greater than' a NaN value (unlike Math.max which does the
658 protected static float max(float f1, float f2)
662 return Float.isNaN(f2) ? f1 : f2;
666 return Float.isNaN(f2) ? f1 : Math.max(f1, f2);
671 * Answers true if this store has no features, else false
675 public boolean isEmpty()
677 boolean hasFeatures = (contactFeatureStarts != null
678 && !contactFeatureStarts
680 || (nonPositionalFeatures != null && !nonPositionalFeatures
682 || (features != null && features.size() > 0);
688 * Answers the set of distinct feature groups stored, possibly including null,
689 * as an unmodifiable view of the set. The parameter determines whether the
690 * groups for positional or for non-positional features are returned.
692 * @param positionalFeatures
695 public Set<String> getFeatureGroups(boolean positionalFeatures)
697 if (positionalFeatures)
699 return Collections.unmodifiableSet(positionalFeatureGroups);
703 return nonPositionalFeatureGroups == null ? Collections
704 .<String> emptySet() : Collections
705 .unmodifiableSet(nonPositionalFeatureGroups);
710 * Answers the number of positional (or non-positional) features stored.
711 * Contact features count as 1.
716 public int getFeatureCount(boolean positional)
720 return nonPositionalFeatures == null ? 0 : nonPositionalFeatures
726 if (contactFeatureStarts != null)
728 // note a contact feature (start/end) counts as one
729 size += contactFeatureStarts.size();
732 if (features != null)
734 size += features.size();
741 * Answers the total length of positional features (or zero if there are
742 * none). Contact features contribute a value of 1 to the total.
746 public int getTotalFeatureLength()
752 * Answers the minimum score held for positional or non-positional features.
753 * This may be Float.NaN if there are no features, are none has a non-NaN
759 public float getMinimumScore(boolean positional)
761 return positional ? positionalMinScore : nonPositionalMinScore;
765 * Answers the maximum score held for positional or non-positional features.
766 * This may be Float.NaN if there are no features, are none has a non-NaN
772 public float getMaximumScore(boolean positional)
774 return positional ? positionalMaxScore : nonPositionalMaxScore;
778 * Answers a list of all either positional or non-positional features whose
779 * feature group matches the given group (which may be null)
785 public List<SequenceFeature> getFeaturesForGroup(boolean positional,
788 List<SequenceFeature> result = new ArrayList<>();
791 * if we know features don't include the target group, no need
792 * to inspect them for matches
794 if (positional && !positionalFeatureGroups.contains(group)
795 || !positional && !nonPositionalFeatureGroups.contains(group))
800 List<SequenceFeature> sfs = positional ? getPositionalFeatures()
801 : getNonPositionalFeatures();
802 for (SequenceFeature sf : sfs)
804 String featureGroup = sf.getFeatureGroup();
805 if (group == null && featureGroup == null || group != null
806 && group.equals(featureGroup))
815 * Adds the shift amount to the start and end of all positional features whose
816 * start position is at or after fromPosition. Returns true if at least one
817 * feature was shifted, else false.
819 * @param fromPosition
823 public synchronized boolean shiftFeatures(int fromPosition, int shiftBy)
826 * Because begin and end are final fields (to ensure the data store's
827 * integrity), we have to delete each feature and re-add it as amended.
828 * (Although a simple shift of all values would preserve data integrity!)
830 boolean modified = false;
831 for (SequenceFeature sf : getPositionalFeatures())
833 if (sf.getBegin() >= fromPosition)
836 int newBegin = sf.getBegin() + shiftBy;
837 int newEnd = sf.getEnd() + shiftBy;
840 * sanity check: don't shift left of the first residue
844 newBegin = Math.max(1, newBegin);
845 SequenceFeature sf2 = new SequenceFeature(sf, newBegin, newEnd,
846 sf.getFeatureGroup(), sf.getScore());