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 java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.List;
29 import intervalstore.api.IntervalStoreI;
30 import intervalstore.impl.BinarySearcher;
31 import intervalstore.impl.BinarySearcher.Compare;
32 import intervalstore.impl.IntervalStore;
33 import jalview.datamodel.SequenceFeature;
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
186 : nonPositionalFeatures.contains(feature);
189 if (feature.isContactFeature())
191 return contactFeatureStarts == null ? false
192 : listContains(contactFeatureStarts, feature);
195 return features == null ? false : features.contains(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. The feature
221 * group is added to the set of distinct feature groups for non-positional
222 * features. This method allows duplicate features, so test before calling to
227 protected boolean addNonPositionalFeature(SequenceFeature feature)
229 if (nonPositionalFeatures == null)
231 nonPositionalFeatures = new ArrayList<>();
234 nonPositionalFeatures.add(feature);
236 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
242 * Adds one feature to the IntervalStore that can manage nested features
243 * (creating the IntervalStore if necessary)
245 protected synchronized void addNestedFeature(SequenceFeature feature)
247 if (features == null)
249 features = new IntervalStore<>();
251 features.add(feature);
255 * Add a contact feature to the lists that hold them ordered by start (first
256 * contact) and by end (second contact) position, ensuring the lists remain
257 * ordered, and returns true. This method allows duplicate features to be
258 * added, so test before calling to avoid this.
263 protected synchronized boolean addContactFeature(SequenceFeature feature)
265 if (contactFeatureStarts == null)
267 contactFeatureStarts = new ArrayList<>();
269 if (contactFeatureEnds == null)
271 contactFeatureEnds = new ArrayList<>();
275 * insert into list sorted by start (first contact position):
276 * binary search the sorted list to find the insertion point
278 int insertPosition = BinarySearcher.findFirst(contactFeatureStarts,
279 true, Compare.GE, feature.getBegin());
280 contactFeatureStarts.add(insertPosition, feature);
283 * insert into list sorted by end (second contact position):
284 * binary search the sorted list to find the insertion point
286 insertPosition = BinarySearcher.findFirst(contactFeatureEnds, false,
287 Compare.GE, feature.getEnd());
288 contactFeatureEnds.add(insertPosition, feature);
294 * Answers true if the list contains the feature, else false. This method is
295 * optimised for the condition that the list is sorted on feature start
296 * position ascending, and will give unreliable results if this does not hold.
302 protected static boolean listContains(List<SequenceFeature> features,
303 SequenceFeature feature)
305 if (features == null || feature == null)
311 * locate the first entry in the list which does not precede the feature
313 // int pos = binarySearch(features,
314 // SearchCriterion.byFeature(feature, RangeComparator.BY_START_POSITION));
315 int pos = BinarySearcher.findFirst(features, true, Compare.GE,
317 int len = features.size();
320 SequenceFeature sf = features.get(pos);
321 if (sf.getBegin() > feature.getBegin())
323 return false; // no match found
325 if (sf.equals(feature))
335 * Returns a (possibly empty) list of features whose extent overlaps the given
336 * range. The returned list is not ordered. Contact features are included if
337 * either of the contact points lies within the range.
340 * start position of overlap range (inclusive)
342 * end position of overlap range (inclusive)
345 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
347 List<SequenceFeature> result = new ArrayList<>();
349 findContactFeatures(start, end, result);
351 if (features != null)
353 result.addAll(features.findOverlaps(start, end));
360 * Adds contact features to the result list where either the second or the
361 * first contact position lies within the target range
367 protected void findContactFeatures(long from, long to,
368 List<SequenceFeature> result)
370 if (contactFeatureStarts != null)
372 findContactStartOverlaps(from, to, result);
374 if (contactFeatureEnds != null)
376 findContactEndOverlaps(from, to, result);
381 * Adds to the result list any contact features whose end (second contact
382 * point), but not start (first contact point), lies in the query from-to
389 protected void findContactEndOverlaps(long from, long to,
390 List<SequenceFeature> result)
393 * find the first contact feature (if any)
394 * whose end point is not before the target range
396 int index = BinarySearcher.findFirst(contactFeatureEnds, false,
397 Compare.GE, (int) from);
399 while (index < contactFeatureEnds.size())
401 SequenceFeature sf = contactFeatureEnds.get(index);
402 if (!sf.isContactFeature())
404 jalview.bin.Console.errPrintln("Error! non-contact feature type " + sf.getType()
405 + " in contact features list");
410 int begin = sf.getBegin();
411 if (begin >= from && begin <= to)
414 * this feature's first contact position lies in the search range
415 * so we don't include it in results a second time
421 if (sf.getEnd() > to)
424 * this feature (and all following) has end point after the target range
430 * feature has end >= from and end <= to
431 * i.e. contact end point lies within overlap search range
439 * Adds contact features whose start position lies in the from-to range to the
446 protected void findContactStartOverlaps(long from, long to,
447 List<SequenceFeature> result)
449 int index = BinarySearcher.findFirst(contactFeatureStarts, true,
450 Compare.GE, (int) from);
452 while (index < contactFeatureStarts.size())
454 SequenceFeature sf = contactFeatureStarts.get(index);
455 if (!sf.isContactFeature())
457 jalview.bin.Console.errPrintln("Error! non-contact feature " + sf.toString()
458 + " in contact features list");
462 if (sf.getBegin() > to)
465 * this feature's start (and all following) follows the target range
471 * feature has begin >= from and begin <= to
472 * i.e. contact start point lies within overlap search range
480 * Answers a list of all positional features stored, in no guaranteed order
484 public List<SequenceFeature> getPositionalFeatures()
486 List<SequenceFeature> result = new ArrayList<>();
489 * add any contact features - from the list by start position
491 if (contactFeatureStarts != null)
493 result.addAll(contactFeatureStarts);
497 * add any nested features
499 if (features != null)
501 result.addAll(features);
508 * Answers a list of all contact features. If there are none, returns an
509 * immutable empty list.
513 public List<SequenceFeature> getContactFeatures()
515 if (contactFeatureStarts == null)
517 return Collections.emptyList();
519 return new ArrayList<>(contactFeatureStarts);
523 * Answers a list of all non-positional features. If there are none, returns
524 * an immutable empty list.
528 public List<SequenceFeature> getNonPositionalFeatures()
530 if (nonPositionalFeatures == null)
532 return Collections.emptyList();
534 return new ArrayList<>(nonPositionalFeatures);
538 * Deletes the given feature from the store, returning true if it was found
539 * (and deleted), else false. This method makes no assumption that the feature
540 * is in the 'expected' place in the store, in case it has been modified since
545 public synchronized boolean delete(SequenceFeature sf)
547 boolean removed = false;
550 * try contact positions (and if found, delete
551 * from both lists of contact positions)
553 if (!removed && contactFeatureStarts != null)
555 removed = contactFeatureStarts.remove(sf);
558 contactFeatureEnds.remove(sf);
562 boolean removedNonPositional = false;
565 * if not found, try non-positional features
567 if (!removed && nonPositionalFeatures != null)
569 removedNonPositional = nonPositionalFeatures.remove(sf);
570 removed = removedNonPositional;
574 * if not found, try nested features
576 if (!removed && features != null)
578 removed = features.remove(sf);
590 * Rescan all features to recompute any cached values after an entry has been
591 * deleted. This is expected to be an infrequent event, so performance here is
594 protected synchronized void rescanAfterDelete()
596 positionalFeatureGroups.clear();
597 nonPositionalFeatureGroups.clear();
599 positionalMinScore = Float.NaN;
600 positionalMaxScore = Float.NaN;
601 nonPositionalMinScore = Float.NaN;
602 nonPositionalMaxScore = Float.NaN;
605 * scan non-positional features for groups and scores
607 for (SequenceFeature sf : getNonPositionalFeatures())
609 nonPositionalFeatureGroups.add(sf.getFeatureGroup());
610 float score = sf.getScore();
611 nonPositionalMinScore = min(nonPositionalMinScore, score);
612 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
616 * scan positional features for groups, scores and extents
618 for (SequenceFeature sf : getPositionalFeatures())
620 positionalFeatureGroups.add(sf.getFeatureGroup());
621 float score = sf.getScore();
622 positionalMinScore = min(positionalMinScore, score);
623 positionalMaxScore = max(positionalMaxScore, score);
624 totalExtent += getFeatureLength(sf);
629 * A helper method to return the minimum of two floats, where a non-NaN value
630 * is treated as 'less than' a NaN value (unlike Math.min which does the
636 protected static float min(float f1, float f2)
640 return Float.isNaN(f2) ? f1 : f2;
644 return Float.isNaN(f2) ? f1 : Math.min(f1, f2);
649 * A helper method to return the maximum of two floats, where a non-NaN value
650 * is treated as 'greater than' a NaN value (unlike Math.max which does the
656 protected static float max(float f1, float f2)
660 return Float.isNaN(f2) ? f1 : f2;
664 return Float.isNaN(f2) ? f1 : Math.max(f1, f2);
669 * Answers true if this store has no features, else false
673 public boolean isEmpty()
675 boolean hasFeatures = (contactFeatureStarts != null
676 && !contactFeatureStarts.isEmpty())
677 || (nonPositionalFeatures != null
678 && !nonPositionalFeatures.isEmpty())
679 || (features != null && features.size() > 0);
685 * Answers the set of distinct feature groups stored, possibly including null,
686 * as an unmodifiable view of the set. The parameter determines whether the
687 * groups for positional or for non-positional features are returned.
689 * @param positionalFeatures
692 public Set<String> getFeatureGroups(boolean positionalFeatures)
694 if (positionalFeatures)
696 return Collections.unmodifiableSet(positionalFeatureGroups);
700 return nonPositionalFeatureGroups == null
701 ? Collections.<String> emptySet()
702 : Collections.unmodifiableSet(nonPositionalFeatureGroups);
707 * Answers the number of positional (or non-positional) features stored.
708 * Contact features count as 1.
713 public int getFeatureCount(boolean positional)
717 return nonPositionalFeatures == null ? 0
718 : nonPositionalFeatures.size();
723 if (contactFeatureStarts != null)
725 // note a contact feature (start/end) counts as one
726 size += contactFeatureStarts.size();
729 if (features != null)
731 size += features.size();
738 * Answers the total length of positional features (or zero if there are
739 * none). Contact features contribute a value of 1 to the total.
743 public int getTotalFeatureLength()
749 * Answers the minimum score held for positional or non-positional features.
750 * This may be Float.NaN if there are no features, are none has a non-NaN
756 public float getMinimumScore(boolean positional)
758 return positional ? positionalMinScore : nonPositionalMinScore;
762 * Answers the maximum score held for positional or non-positional features.
763 * This may be Float.NaN if there are no features, are none has a non-NaN
769 public float getMaximumScore(boolean positional)
771 return positional ? positionalMaxScore : nonPositionalMaxScore;
775 * Answers a list of all either positional or non-positional features whose
776 * feature group matches the given group (which may be null)
782 public List<SequenceFeature> getFeaturesForGroup(boolean positional,
785 List<SequenceFeature> result = new ArrayList<>();
788 * if we know features don't include the target group, no need
789 * to inspect them for matches
791 if (positional && !positionalFeatureGroups.contains(group)
792 || !positional && !nonPositionalFeatureGroups.contains(group))
797 List<SequenceFeature> sfs = positional ? getPositionalFeatures()
798 : getNonPositionalFeatures();
799 for (SequenceFeature sf : sfs)
801 String featureGroup = sf.getFeatureGroup();
802 if (group == null && featureGroup == null
803 || group != null && group.equals(featureGroup))
812 * Adds the shift amount to the start and end of all positional features whose
813 * start position is at or after fromPosition. Returns true if at least one
814 * feature was shifted, else false.
816 * @param fromPosition
820 public synchronized boolean shiftFeatures(int fromPosition, int shiftBy)
823 * Because begin and end are final fields (to ensure the data store's
824 * integrity), we have to delete each feature and re-add it as amended.
825 * (Although a simple shift of all values would preserve data integrity!)
827 boolean modified = false;
828 for (SequenceFeature sf : getPositionalFeatures())
830 if (sf.getBegin() >= fromPosition)
833 int newBegin = sf.getBegin() + shiftBy;
834 int newEnd = sf.getEnd() + shiftBy;
837 * sanity check: don't shift left of the first residue
841 newBegin = Math.max(1, newBegin);
842 SequenceFeature sf2 = new SequenceFeature(sf, newBegin, newEnd,
843 sf.getFeatureGroup(), sf.getScore());