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;
24 import jalview.util.Platform;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashSet;
30 import java.util.List;
33 import intervalstore.api.IntervalStoreI;
34 import intervalstore.impl.BinarySearcher;
35 import intervalstore.impl.BinarySearcher.Compare;
37 public class FeatureStore
40 * track last start for quick insertion of ordered features
42 protected int lastStart = -1;
44 protected int lastContactStart = -1;
47 * Non-positional features have no (zero) start/end position.
48 * Kept as a separate list in case this criterion changes in future.
50 List<SequenceFeature> nonPositionalFeatures;
53 * contact features ordered by first contact position
55 List<SequenceFeature> contactFeatureStarts;
58 * contact features ordered by second contact position
60 List<SequenceFeature> contactFeatureEnds;
63 * IntervalStore holds remaining features and provides efficient
64 * query for features overlapping any given interval
66 IntervalStoreI<SequenceFeature> features;
69 * Feature groups represented in stored positional features
70 * (possibly including null)
72 Set<String> positionalFeatureGroups;
75 * Feature groups represented in stored non-positional features
76 * (possibly including null)
78 Set<String> nonPositionalFeatureGroups;
81 * the total length of all positional features; contact features count 1 to
82 * the total and 1 to size(), consistent with an average 'feature length' of 1
86 float positionalMinScore;
88 float positionalMaxScore;
90 float nonPositionalMinScore;
92 float nonPositionalMaxScore;
94 public final static int INTERVAL_STORE_DEFAULT = -1;
97 * original NCList-based IntervalStore
99 public final static int INTERVAL_STORE_NCLIST_OBJECT = 0;
102 * linked-list IntervalStore
104 public final static int INTERVAL_STORE_LINKED_LIST = 1;
107 * NCList as array buffer IntervalStore
109 public final static int INTERVAL_STORE_NCARRAY = 3;
111 static final int intervalStoreJavaOption = INTERVAL_STORE_NCLIST_OBJECT;
113 private final static boolean isJSLinkedTest = false;
115 static final int intervalStoreJSOption = (isJSLinkedTest
116 ? INTERVAL_STORE_LINKED_LIST
117 : INTERVAL_STORE_NCARRAY);
119 // TODO: compare performance in real situations using
120 // INTERVAL_STORE_LINKED_LIST;
123 * Answers the 'length' of the feature, counting 0 for non-positional features
124 * and 1 for contact features
129 protected static int getFeatureLength(SequenceFeature feature)
131 if (feature.isNonPositional())
135 if (feature.isContactFeature())
139 return 1 + feature.getEnd() - feature.getBegin();
143 * Answers true if the list contains the feature, else false. This method is
144 * optimised for the condition that the list is sorted on feature start
145 * position ascending, and will give unreliable results if this does not hold.
151 public boolean listContains(List<SequenceFeature> list,
152 SequenceFeature feature)
154 if (list == null || feature == null)
160 * locate the first entry in the list which does not precede the feature
162 int begin = feature.begin;
163 int pos = BinarySearcher.findFirst(list, true, Compare.GE, begin);
164 int len = list.size();
167 SequenceFeature sf = list.get(pos);
168 if (sf.begin > begin)
170 return false; // no match found
172 if (sf.equals(feature))
182 * A helper method to return the maximum of two floats, where a non-NaN value
183 * is treated as 'greater than' a NaN value (unlike Math.max which does the
189 protected static float max(float f1, float f2)
193 return Float.isNaN(f2) ? f1 : f2;
197 return Float.isNaN(f2) ? f1 : Math.max(f1, f2);
202 * A helper method to return the minimum of two floats, where a non-NaN value
203 * is treated as 'less than' a NaN value (unlike Math.min which does the
209 protected static float min(float f1, float f2)
213 return Float.isNaN(f2) ? f1 : f2;
217 return Float.isNaN(f2) ? f1 : Math.min(f1, f2);
222 * standard constructor
224 public FeatureStore()
226 this(INTERVAL_STORE_DEFAULT);
230 * constructor for testing only
232 public FeatureStore(int intervalStoreType)
236 // ? new intervalstore.nonc.IntervalStore<>(true)
237 // : new intervalstore.impl.IntervalStore<>();
238 getIntervalStore(intervalStoreType);
239 positionalFeatureGroups = new HashSet<>();
240 nonPositionalFeatureGroups = new HashSet<>();
241 positionalMinScore = Float.NaN;
242 positionalMaxScore = Float.NaN;
243 nonPositionalMinScore = Float.NaN;
244 nonPositionalMaxScore = Float.NaN;
246 // we only construct nonPositionalFeatures, contactFeatures if we need to
249 private IntervalStoreI<SequenceFeature> getIntervalStore(int type)
251 switch (type != INTERVAL_STORE_DEFAULT ? type : //
253 ? intervalStoreJSOption
254 : intervalStoreJavaOption)
257 case INTERVAL_STORE_NCLIST_OBJECT:
258 return new intervalstore.impl.IntervalStore<>();
259 case INTERVAL_STORE_NCARRAY:
260 return new intervalstore.nonc.IntervalStore<>();
261 case INTERVAL_STORE_LINKED_LIST:
262 return new intervalstore.nonc.IntervalStore0<>();
267 * Add a contact feature to the lists that hold them ordered by start (first
268 * contact) and by end (second contact) position, ensuring the lists remain
269 * ordered, and returns true. This method allows duplicate features to be
270 * added, so test before calling to avoid this.
275 protected synchronized boolean addContactFeature(SequenceFeature feature)
277 if (contactFeatureStarts == null)
279 contactFeatureStarts = new ArrayList<>();
280 contactFeatureEnds = new ArrayList<>();
284 * insert into list sorted by start (first contact position):
285 * binary search the sorted list to find the insertion point
287 int insertAt = BinarySearcher.findFirst(contactFeatureStarts, true,
288 Compare.GE, feature.begin);
289 contactFeatureStarts.add(insertAt, feature);
291 * insert into list sorted by end (second contact position):
292 * binary search the sorted list to find the insertion point
294 contactFeatureEnds.add(findFirstEnd(contactFeatureEnds, feature.end),
301 * Adds one sequence feature to the store, and returns true, unless the
302 * feature is already contained in the store, in which case this method
303 * returns false. Containment is determined by SequenceFeature.equals()
308 public boolean addFeature(SequenceFeature feature)
310 if (feature.isContactFeature())
312 if (containsContactFeature(feature))
316 positionalFeatureGroups.add(feature.getFeatureGroup());
317 if (feature.begin > lastContactStart)
319 lastContactStart = feature.begin;
321 addContactFeature(feature);
323 else if (feature.isNonPositional())
325 if (containsNonPositionalFeature(feature))
330 addNonPositionalFeature(feature);
334 if (!features.add(feature, false))
338 positionalFeatureGroups.add(feature.getFeatureGroup());
339 if (feature.begin > lastStart)
341 lastStart = feature.begin;
346 * record the total extent of positional features, to make
347 * getTotalFeatureLength possible; we count the length of a
348 * contact feature as 1
350 totalExtent += getFeatureLength(feature);
353 * record the minimum and maximum score for positional
354 * and non-positional features
356 float score = feature.getScore();
357 if (!Float.isNaN(score))
359 if (feature.isNonPositional())
361 nonPositionalMinScore = min(nonPositionalMinScore, score);
362 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
366 positionalMinScore = min(positionalMinScore, score);
367 positionalMaxScore = max(positionalMaxScore, score);
374 private void addFeaturesForGroup(String group,
375 Collection<SequenceFeature> sfs, List<SequenceFeature> result)
381 for (SequenceFeature sf : sfs)
383 String featureGroup = sf.getFeatureGroup();
384 if (group == null && featureGroup == null
385 || group != null && group.equals(featureGroup))
393 * Adds the feature to the list of non-positional features (with lazy
394 * instantiation of the list if it is null), and returns true. The feature
395 * group is added to the set of distinct feature groups for non-positional
396 * features. This method allows duplicate features, so test before calling to
401 protected boolean addNonPositionalFeature(SequenceFeature feature)
403 if (nonPositionalFeatures == null)
405 nonPositionalFeatures = new ArrayList<>();
408 nonPositionalFeatures.add(feature);
410 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
416 * Answers true if this store contains the given feature (testing by
417 * SequenceFeature.equals), else false
422 public boolean contains(SequenceFeature feature)
424 if (feature.isNonPositional())
426 return containsNonPositionalFeature(feature);
429 if (feature.isContactFeature())
431 return containsContactFeature(feature);
434 return containsPositionalFeature(feature);
438 private boolean containsPositionalFeature(SequenceFeature feature)
440 return features == null || feature.begin > lastStart ? false
441 : features.contains(feature);
445 * Answers true if this store already contains a contact feature equal to the
446 * given feature (by {@code SequenceFeature.equals()} test), else false
451 private boolean containsContactFeature(SequenceFeature feature)
453 return contactFeatureStarts != null && feature.begin <= lastContactStart
454 && listContains(contactFeatureStarts, feature);
458 * Answers true if this store already contains a non-positional feature equal
459 * to the given feature (by {@code SequenceFeature.equals()} test), else false
464 private boolean containsNonPositionalFeature(SequenceFeature feature)
466 return nonPositionalFeatures == null ? false
467 : nonPositionalFeatures.contains(feature);
471 * Deletes the given feature from the store, returning true if it was found
472 * (and deleted), else false. This method makes no assumption that the feature
473 * is in the 'expected' place in the store, in case it has been modified since
478 public synchronized boolean delete(SequenceFeature sf)
480 boolean removed = false;
483 * try contact positions (and if found, delete
484 * from both lists of contact positions)
486 if (!removed && contactFeatureStarts != null)
488 removed = contactFeatureStarts.remove(sf);
491 contactFeatureEnds.remove(sf);
496 * if not found, try non-positional features
498 if (!removed && nonPositionalFeatures != null)
500 removed = nonPositionalFeatures.remove(sf);
504 * if not found, try nested features
506 if (!removed && features != null)
508 removed = features.remove(sf);
519 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
521 return findOverlappingFeatures(start, end, null);
524 public List<SequenceFeature> getContactFeatures()
526 return getContactFeatures(new ArrayList<>());
530 * Answers a list of all contact features. If there are none, returns an
531 * immutable empty list.
535 public List<SequenceFeature> getContactFeatures(
536 List<SequenceFeature> result)
538 if (contactFeatureStarts != null)
540 result.addAll(contactFeatureStarts);
546 * Answers the number of positional (or non-positional) features stored.
547 * Contact features count as 1.
552 public int getFeatureCount(boolean positional)
556 return nonPositionalFeatures == null ? 0
557 : nonPositionalFeatures.size();
560 return (contactFeatureStarts == null ? 0 : contactFeatureStarts.size())
565 * Answers the set of distinct feature groups stored, possibly including null,
566 * as an unmodifiable view of the set. The parameter determines whether the
567 * groups for positional or for non-positional features are returned.
569 * @param positionalFeatures
572 public Set<String> getFeatureGroups(boolean positionalFeatures)
574 if (positionalFeatures)
576 return Collections.unmodifiableSet(positionalFeatureGroups);
580 return nonPositionalFeatureGroups == null
581 ? Collections.<String> emptySet()
582 : Collections.unmodifiableSet(nonPositionalFeatureGroups);
586 public Collection<SequenceFeature> getFeatures()
592 * Answers a list of all either positional or non-positional features whose
593 * feature group matches the given group (which may be null)
599 public List<SequenceFeature> getFeaturesForGroup(boolean positional,
602 List<SequenceFeature> result = new ArrayList<>();
605 * if we know features don't include the target group, no need
606 * to inspect them for matches
608 if (positional && !positionalFeatureGroups.contains(group)
609 || !positional && !nonPositionalFeatureGroups.contains(group))
616 addFeaturesForGroup(group, contactFeatureStarts, result);
617 addFeaturesForGroup(group, features, result);
621 addFeaturesForGroup(group, nonPositionalFeatures, result);
627 * Answers the maximum score held for positional or non-positional features.
628 * This may be Float.NaN if there are no features, are none has a non-NaN
634 public float getMaximumScore(boolean positional)
636 return positional ? positionalMaxScore : nonPositionalMaxScore;
640 * Answers the minimum score held for positional or non-positional features.
641 * This may be Float.NaN if there are no features, are none has a non-NaN
647 public float getMinimumScore(boolean positional)
649 return positional ? positionalMinScore : nonPositionalMinScore;
652 public List<SequenceFeature> getNonPositionalFeatures()
654 return getNonPositionalFeatures(new ArrayList<>());
658 * Answers a list of all non-positional features. If there are none, returns
659 * an immutable empty list.
663 public List<SequenceFeature> getNonPositionalFeatures(
664 List<SequenceFeature> result)
666 if (nonPositionalFeatures != null)
668 result.addAll(nonPositionalFeatures);
673 public List<SequenceFeature> getPositionalFeatures()
675 return getPositionalFeatures(new ArrayList<>());
679 * Answers a list of all positional features stored, in no guaranteed order
683 public List<SequenceFeature> getPositionalFeatures(
684 List<SequenceFeature> result)
688 * add any contact features - from the list by start position
690 if (contactFeatureStarts != null)
692 result.addAll(contactFeatureStarts);
696 * add any nested features
698 if (features != null)
700 result.addAll(features);
707 * Answers the total length of positional features (or zero if there are
708 * none). Contact features contribute a value of 1 to the total.
712 public int getTotalFeatureLength()
718 * Answers true if this store has no features, else false
722 public boolean isEmpty()
724 boolean hasFeatures = (contactFeatureStarts != null
725 && !contactFeatureStarts.isEmpty())
726 || (nonPositionalFeatures != null
727 && !nonPositionalFeatures.isEmpty())
728 || features.size() > 0;
734 * Rescan all features to recompute any cached values after an entry has been
735 * deleted. This is expected to be an infrequent event, so performance here is
738 protected synchronized void rescanAfterDelete()
740 positionalFeatureGroups.clear();
741 nonPositionalFeatureGroups.clear();
743 positionalMinScore = Float.NaN;
744 positionalMaxScore = Float.NaN;
745 nonPositionalMinScore = Float.NaN;
746 nonPositionalMaxScore = Float.NaN;
748 * scan non-positional features for groups and scores
750 if (nonPositionalFeatures != null)
752 List<SequenceFeature> list = nonPositionalFeatures;
753 for (int i = 0, n = list.size(); i < n; i++)
755 SequenceFeature sf = list.get(i);
756 nonPositionalFeatureGroups.add(sf.getFeatureGroup());
757 float score = sf.getScore();
758 nonPositionalMinScore = min(nonPositionalMinScore, score);
759 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
764 * scan positional features for groups, scores and extents
767 rescanPositional(contactFeatureStarts);
768 rescanPositional(features);
771 private void rescanPositional(Collection<SequenceFeature> sfs)
777 for (SequenceFeature sf : sfs)
779 positionalFeatureGroups.add(sf.getFeatureGroup());
780 float score = sf.getScore();
781 positionalMinScore = min(positionalMinScore, score);
782 positionalMaxScore = max(positionalMaxScore, score);
783 totalExtent += getFeatureLength(sf);
788 * Adds the shift amount to the start and end of all positional features whose
789 * start position is at or after fromPosition. Returns true if at least one
790 * feature was shifted, else false.
792 * @param fromPosition
796 public synchronized boolean shiftFeatures(int fromPosition, int shiftBy)
799 * Because begin and end are final fields (to ensure the data store's
800 * integrity), we have to delete each feature and re-add it as amended.
801 * (Although a simple shift of all values would preserve data integrity!)
803 boolean modified = false;
804 List<SequenceFeature> list = getPositionalFeatures();
805 for (int i = 0, n = list.size(); i < n; i++)
807 SequenceFeature sf = list.get(i);
808 if (sf.getBegin() >= fromPosition)
811 int newBegin = sf.getBegin() + shiftBy;
812 int newEnd = sf.getEnd() + shiftBy;
815 * sanity check: don't shift left of the first residue
819 newBegin = Math.max(1, newBegin);
820 SequenceFeature sf2 = new SequenceFeature(sf, newBegin, newEnd,
821 sf.getFeatureGroup(), sf.getScore());
831 * Answers the position (0, 1...) in the list of the first entry whose end
832 * position is not less than {@ pos}. If no such entry is found, answers the
833 * length of the list.
839 protected int findFirstEnd(List<SequenceFeature> list, long pos)
841 return BinarySearcher.findFirst(list, false, Compare.GE, (int) pos);
845 * Adds contact features to the result list where either the second or the
846 * first contact position lies within the target range
852 protected void findContactFeatures(long from, long to,
853 List<SequenceFeature> result)
855 if (contactFeatureStarts != null)
857 findContactStartOverlaps(from, to, result);
858 findContactEndOverlaps(from, to, result);
863 * Adds to the result list any contact features whose end (second contact
864 * point), but not start (first contact point), lies in the query from-to
871 private void findContactEndOverlaps(long from, long to,
872 List<SequenceFeature> result)
875 * find the first contact feature (if any)
876 * whose end point is not before the target range
878 int index = findFirstEnd(contactFeatureEnds, from);
880 int n = contactFeatureEnds.size();
883 SequenceFeature sf = contactFeatureEnds.get(index);
884 if (!sf.isContactFeature())
886 System.err.println("Error! non-contact feature type " + sf.getType()
887 + " in contact features list");
892 int begin = sf.getBegin();
893 if (begin >= from && begin <= to)
896 * this feature's first contact position lies in the search range
897 * so we don't include it in results a second time
903 if (sf.getEnd() > to)
906 * this feature (and all following) has end point after the target range
912 * feature has end >= from and end <= to
913 * i.e. contact end point lies within overlap search range
921 * Adds contact features whose start position lies in the from-to range to the
928 private void findContactStartOverlaps(long from, long to,
929 List<SequenceFeature> result)
931 int index = BinarySearcher.findFirst(contactFeatureStarts, true,
932 Compare.GE, (int) from);
934 while (index < contactFeatureStarts.size())
936 SequenceFeature sf = contactFeatureStarts.get(index);
937 if (!sf.isContactFeature())
939 System.err.println("Error! non-contact feature " + sf.toString()
940 + " in contact features list");
944 if (sf.getBegin() > to)
947 * this feature's start (and all following) follows the target range
953 * feature has begin >= from and begin <= to
954 * i.e. contact start point lies within overlap search range
962 * Returns a (possibly empty) list of features whose extent overlaps the given
963 * range. The returned list is not ordered. Contact features are included if
964 * either of the contact points lies within the range. If the {@code result}
965 * parameter is not null, new entries are added to this list and the (possibly
966 * extended) list returned.
969 * start position of overlap range (inclusive)
971 * end position of overlap range (inclusive)
975 public List<SequenceFeature> findOverlappingFeatures(long start, long end,
976 List<SequenceFeature> result)
980 result = new ArrayList<>();
983 findContactFeatures(start, end, result);
984 features.findOverlaps(start, end, result);