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.Arrays;
27 import java.util.Collections;
28 import java.util.Comparator;
29 import java.util.HashSet;
30 import java.util.List;
33 import intervalstore.api.IntervalStoreI;
34 import intervalstore.impl.BinarySearcher;
35 import intervalstore.impl.IntervalStore;
38 * A data store for a set of sequence features that supports efficient lookup of
39 * features overlapping a given range. Intended for (but not limited to) storage
40 * of features for one sequence and feature type.
45 public class FeatureStore
48 * Non-positional features have no (zero) start/end position.
49 * Kept as a separate list in case this criterion changes in future.
51 List<SequenceFeature> nonPositionalFeatures;
54 * contact features ordered by first contact position
56 List<SequenceFeature> contactFeatureStarts;
59 * contact features ordered by second contact position
61 List<SequenceFeature> contactFeatureEnds;
64 * IntervalStore holds remaining features and provides efficient
65 * query for features overlapping any given interval
67 IntervalStoreI<SequenceFeature> features;
70 * Feature groups represented in stored positional features
71 * (possibly including null)
73 Set<String> positionalFeatureGroups;
76 * Feature groups represented in stored non-positional features
77 * (possibly including null)
79 Set<String> nonPositionalFeatureGroups;
82 * the total length of all positional features; contact features count 1 to
83 * the total and 1 to size(), consistent with an average 'feature length' of 1
87 float positionalMinScore;
89 float positionalMaxScore;
91 float nonPositionalMinScore;
93 float nonPositionalMaxScore;
95 private ArrayList<SequenceFeature> featuresList;
100 public FeatureStore()
102 features = new IntervalStore<>();
103 featuresList = new ArrayList<>();
104 positionalFeatureGroups = new HashSet<>();
105 nonPositionalFeatureGroups = new HashSet<>();
106 positionalMinScore = Float.NaN;
107 positionalMaxScore = Float.NaN;
108 nonPositionalMinScore = Float.NaN;
109 nonPositionalMaxScore = Float.NaN;
111 // we only construct nonPositionalFeatures, contactFeatures if we need to
115 * Adds one sequence feature to the store, and returns true, unless the
116 * feature is already contained in the store, in which case this method
117 * returns false. Containment is determined by SequenceFeature.equals()
123 public boolean addFeature(SequenceFeature feature)
125 if (contains(feature))
131 * keep a record of feature groups
133 if (!feature.isNonPositional())
135 positionalFeatureGroups.add(feature.getFeatureGroup());
138 if (feature.isContactFeature())
140 addContactFeature(feature);
142 else if (feature.isNonPositional())
144 addNonPositionalFeature(feature);
148 addNestedFeature(feature);
152 * record the total extent of positional features, to make
153 * getTotalFeatureLength possible; we count the length of a
154 * contact feature as 1
156 totalExtent += getFeatureLength(feature);
159 * record the minimum and maximum score for positional
160 * and non-positional features
162 float score = feature.getScore();
163 if (!Float.isNaN(score))
165 if (feature.isNonPositional())
167 nonPositionalMinScore = min(nonPositionalMinScore, score);
168 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
172 positionalMinScore = min(positionalMinScore, score);
173 positionalMaxScore = max(positionalMaxScore, score);
181 * Answers true if this store contains the given feature (testing by
182 * SequenceFeature.equals), else false
187 public boolean contains(SequenceFeature feature)
189 if (feature.isNonPositional())
191 return nonPositionalFeatures == null ? false
192 : nonPositionalFeatures.contains(feature);
195 if (feature.isContactFeature())
197 return contactFeatureStarts == null ? false
198 : listContains(contactFeatureStarts, feature);
201 return features == null ? false : features.contains(feature);
205 * Answers the 'length' of the feature, counting 0 for non-positional features
206 * and 1 for contact features
211 protected static int getFeatureLength(SequenceFeature feature)
213 if (feature.isNonPositional())
217 if (feature.isContactFeature())
221 return 1 + feature.getEnd() - feature.getBegin();
225 * Adds the feature to the list of non-positional features (with lazy
226 * instantiation of the list if it is null), and returns true. The feature
227 * group is added to the set of distinct feature groups for non-positional
228 * features. This method allows duplicate features, so test before calling to
233 protected boolean addNonPositionalFeature(SequenceFeature feature)
235 if (nonPositionalFeatures == null)
237 nonPositionalFeatures = new ArrayList<>();
240 nonPositionalFeatures.add(feature);
242 nonPositionalFeatureGroups.add(feature.getFeatureGroup());
248 * Adds one feature to the IntervalStore that can manage nested features
249 * (creating the IntervalStore if necessary)
251 protected synchronized void addNestedFeature(SequenceFeature feature)
253 if (features == null)
255 features = new IntervalStore<>();
257 features.add(feature);
258 featuresList.add(feature);
262 * Add a contact feature to the lists that hold them ordered by start (first
263 * contact) and by end (second contact) position, ensuring the lists remain
264 * ordered, and returns true. This method allows duplicate features to be
265 * added, so test before calling to avoid this.
270 protected synchronized boolean addContactFeature(SequenceFeature feature)
272 if (contactFeatureStarts == null)
274 contactFeatureStarts = new ArrayList<>();
276 if (contactFeatureEnds == null)
278 contactFeatureEnds = new ArrayList<>();
282 * insert into list sorted by start (first contact position):
283 * binary search the sorted list to find the insertion point
285 int insertPosition = BinarySearcher.findFirst(contactFeatureStarts,
286 f -> f.getBegin() >= feature.getBegin());
287 contactFeatureStarts.add(insertPosition, feature);
290 * insert into list sorted by end (second contact position):
291 * binary search the sorted list to find the insertion point
293 insertPosition = BinarySearcher.findFirst(contactFeatureEnds,
294 f -> f.getEnd() >= feature.getEnd());
295 contactFeatureEnds.add(insertPosition, feature);
301 * Answers true if the list contains the feature, else false. This method is
302 * optimised for the condition that the list is sorted on feature start
303 * position ascending, and will give unreliable results if this does not hold.
309 protected static boolean listContains(List<SequenceFeature> features,
310 SequenceFeature feature)
312 if (features == null || feature == null)
318 * locate the first entry in the list which does not precede the feature
320 // int pos = binarySearch(features,
321 // SearchCriterion.byFeature(feature, RangeComparator.BY_START_POSITION));
322 int pos = BinarySearcher.findFirst(features,
323 val -> val.getBegin() >= feature.getBegin());
324 int len = features.size();
327 SequenceFeature sf = features.get(pos);
328 if (sf.getBegin() > feature.getBegin())
330 return false; // no match found
332 if (sf.equals(feature))
342 * Returns a (possibly empty) list of features whose extent overlaps the given
343 * range. The returned list is not ordered. Contact features are included if
344 * either of the contact points lies within the range.
347 * start position of overlap range (inclusive)
349 * end position of overlap range (inclusive)
353 public List<SequenceFeature> findOverlappingFeatures(long start, long end)
355 List<SequenceFeature> result = new ArrayList<>();
357 findContactFeatures(start, end, result);
359 if (features != null)
361 result.addAll(features.findOverlaps(start, end));
368 * Adds contact features to the result list where either the second or the
369 * first contact position lies within the target range
375 protected void findContactFeatures(long from, long to,
376 List<SequenceFeature> result)
378 if (contactFeatureStarts != null)
380 findContactStartOverlaps(from, to, result);
382 if (contactFeatureEnds != null)
384 findContactEndOverlaps(from, to, result);
389 * Adds to the result list any contact features whose end (second contact
390 * point), but not start (first contact point), lies in the query from-to
397 protected void findContactEndOverlaps(long from, long to,
398 List<SequenceFeature> result)
401 * find the first contact feature (if any)
402 * whose end point is not before the target range
404 int index = BinarySearcher.findFirst(contactFeatureEnds,
405 f -> f.getEnd() >= from);
407 while (index < contactFeatureEnds.size())
409 SequenceFeature sf = contactFeatureEnds.get(index);
410 if (!sf.isContactFeature())
412 System.err.println("Error! non-contact feature type " + sf.getType()
413 + " in contact features list");
418 int begin = sf.getBegin();
419 if (begin >= from && begin <= to)
422 * this feature's first contact position lies in the search range
423 * so we don't include it in results a second time
429 if (sf.getEnd() > to)
432 * this feature (and all following) has end point after the target range
438 * feature has end >= from and end <= to
439 * i.e. contact end point lies within overlap search range
447 * Adds contact features whose start position lies in the from-to range to the
454 protected void findContactStartOverlaps(long from, long to,
455 List<SequenceFeature> result)
457 int index = BinarySearcher.findFirst(contactFeatureStarts,
458 f -> f.getBegin() >= from);
460 while (index < contactFeatureStarts.size())
462 SequenceFeature sf = contactFeatureStarts.get(index);
463 if (!sf.isContactFeature())
465 System.err.println("Error! non-contact feature " + sf.toString()
466 + " in contact features list");
470 if (sf.getBegin() > to)
473 * this feature's start (and all following) follows the target range
479 * feature has begin >= from and begin <= to
480 * i.e. contact start point lies within overlap search range
488 * Answers a list of all positional features stored, in no guaranteed order
493 public List<SequenceFeature> getPositionalFeatures()
495 List<SequenceFeature> result = new ArrayList<>();
498 * add any contact features - from the list by start position
500 if (contactFeatureStarts != null)
502 result.addAll(contactFeatureStarts);
506 * add any nested features
508 if (features != null)
510 result.addAll(features);
517 * Answers a list of all contact features. If there are none, returns an
518 * immutable empty list.
523 public List<SequenceFeature> getContactFeatures()
525 if (contactFeatureStarts == null)
527 return Collections.emptyList();
529 return new ArrayList<>(contactFeatureStarts);
533 * Answers a list of all non-positional features. If there are none, returns
534 * an immutable empty list.
539 public List<SequenceFeature> getNonPositionalFeatures()
541 if (nonPositionalFeatures == null)
543 return Collections.emptyList();
545 return new ArrayList<>(nonPositionalFeatures);
549 * Deletes the given feature from the store, returning true if it was found
550 * (and deleted), else false. This method makes no assumption that the feature
551 * is in the 'expected' place in the store, in case it has been modified since
557 public synchronized boolean delete(SequenceFeature sf)
559 boolean removed = false;
562 * try contact positions (and if found, delete
563 * from both lists of contact positions)
565 if (!removed && contactFeatureStarts != null)
567 removed = contactFeatureStarts.remove(sf);
570 contactFeatureEnds.remove(sf);
574 boolean removedNonPositional = false;
577 * if not found, try non-positional features
579 if (!removed && nonPositionalFeatures != null)
581 removedNonPositional = nonPositionalFeatures.remove(sf);
582 removed = removedNonPositional;
586 * if not found, try nested features
588 if (!removed && features != null)
590 removed = features.remove(sf);
591 featuresList.remove(sf);
603 * Rescan all features to recompute any cached values after an entry has been
604 * deleted. This is expected to be an infrequent event, so performance here is
607 protected synchronized void rescanAfterDelete()
609 positionalFeatureGroups.clear();
610 nonPositionalFeatureGroups.clear();
612 positionalMinScore = Float.NaN;
613 positionalMaxScore = Float.NaN;
614 nonPositionalMinScore = Float.NaN;
615 nonPositionalMaxScore = Float.NaN;
617 * scan non-positional features for groups and scores
619 for (SequenceFeature sf : getNonPositionalFeatures())
621 nonPositionalFeatureGroups.add(sf.getFeatureGroup());
622 float score = sf.getScore();
623 nonPositionalMinScore = min(nonPositionalMinScore, score);
624 nonPositionalMaxScore = max(nonPositionalMaxScore, score);
628 * scan positional features for groups, scores and extents
630 for (SequenceFeature sf : getPositionalFeatures())
632 positionalFeatureGroups.add(sf.getFeatureGroup());
633 float score = sf.getScore();
634 positionalMinScore = min(positionalMinScore, score);
635 positionalMaxScore = max(positionalMaxScore, score);
636 totalExtent += getFeatureLength(sf);
641 * A helper method to return the minimum of two floats, where a non-NaN value
642 * is treated as 'less than' a NaN value (unlike Math.min which does the
648 protected static float min(float f1, float f2)
652 return Float.isNaN(f2) ? f1 : f2;
656 return Float.isNaN(f2) ? f1 : Math.min(f1, f2);
661 * A helper method to return the maximum of two floats, where a non-NaN value
662 * is treated as 'greater than' a NaN value (unlike Math.max which does the
668 protected static float max(float f1, float f2)
672 return Float.isNaN(f2) ? f1 : f2;
676 return Float.isNaN(f2) ? f1 : Math.max(f1, f2);
681 * Answers true if this store has no features, else false
686 public boolean isEmpty()
688 boolean hasFeatures = (contactFeatureStarts != null
689 && !contactFeatureStarts.isEmpty())
690 || (nonPositionalFeatures != null
691 && !nonPositionalFeatures.isEmpty())
692 || (features != null && features.size() > 0);
698 * Answers the set of distinct feature groups stored, possibly including null,
699 * as an unmodifiable view of the set. The parameter determines whether the
700 * groups for positional or for non-positional features are returned.
702 * @param positionalFeatures
706 public Set<String> getFeatureGroups(boolean positionalFeatures)
708 if (positionalFeatures)
710 return Collections.unmodifiableSet(positionalFeatureGroups);
714 return nonPositionalFeatureGroups == null
715 ? Collections.<String> emptySet()
716 : Collections.unmodifiableSet(nonPositionalFeatureGroups);
721 * Answers the number of positional (or non-positional) features stored.
722 * Contact features count as 1.
728 public int getFeatureCount(boolean positional)
732 return nonPositionalFeatures == null ? 0
733 : nonPositionalFeatures.size();
738 if (contactFeatureStarts != null)
740 // note a contact feature (start/end) counts as one
741 size += contactFeatureStarts.size();
744 if (features != null)
746 size += features.size();
753 * Answers the total length of positional features (or zero if there are
754 * none). Contact features contribute a value of 1 to the total.
759 public int getTotalFeatureLength()
765 * Answers the minimum 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
773 public float getMinimumScore(boolean positional)
775 return positional ? positionalMinScore : nonPositionalMinScore;
779 * Answers the maximum score held for positional or non-positional features.
780 * This may be Float.NaN if there are no features, are none has a non-NaN
787 public float getMaximumScore(boolean positional)
789 return positional ? positionalMaxScore : nonPositionalMaxScore;
793 * Answers a list of all either positional or non-positional features whose
794 * feature group matches the given group (which may be null)
801 public List<SequenceFeature> getFeaturesForGroup(boolean positional,
804 List<SequenceFeature> result = new ArrayList<>();
807 * if we know features don't include the target group, no need
808 * to inspect them for matches
810 if (positional && !positionalFeatureGroups.contains(group)
811 || !positional && !nonPositionalFeatureGroups.contains(group))
816 List<SequenceFeature> sfs = positional ? getPositionalFeatures()
817 : getNonPositionalFeatures();
818 for (SequenceFeature sf : sfs)
820 String featureGroup = sf.getFeatureGroup();
821 if (group == null && featureGroup == null
822 || group != null && group.equals(featureGroup))
831 * Adds the shift amount to the start and end of all positional features whose
832 * start position is at or after fromPosition. Returns true if at least one
833 * feature was shifted, else false.
835 * @param fromPosition
840 public synchronized boolean shiftFeatures(int fromPosition, int shiftBy)
843 * Because begin and end are final fields (to ensure the data store's
844 * integrity), we have to delete each feature and re-add it as amended.
845 * (Although a simple shift of all values would preserve data integrity!)
847 boolean modified = false;
848 for (SequenceFeature sf : getPositionalFeatures())
850 if (sf.getBegin() >= fromPosition)
853 int newBegin = sf.getBegin() + shiftBy;
854 int newEnd = sf.getEnd() + shiftBy;
857 * sanity check: don't shift left of the first residue
861 newBegin = Math.max(1, newBegin);
862 SequenceFeature sf2 = new SequenceFeature(sf, newBegin, newEnd,
863 sf.getFeatureGroup(), sf.getScore());
872 /////////////////////// added by Bob Hanson ///////////////////////
874 // The following methods use a linked list of containment in features
875 // rather than IntervalStore. Implemented only for OverviewPanel, because
876 // only that makes calls for start == end in feature overlap requests.
879 // There are two parts --- initialization, and overlap searching.
881 // Initialization involves two steps:
883 // (1) sorting of features by start position using a standard Array.sort with
885 // (2) linking of features, effectively nesting them.
887 // Searching also involves two steps:
889 // (1) binary search for a position within the sorted features array.
890 // (2) traversing the linked lists with an end check to read out the
891 // overlapped features at this position.
893 // All of this is done with very simple standard methods.
895 // single public method:
898 * Find all features containing this position.
901 * @return list of SequenceFeatures
902 * @author Bob Hanson 2019.07.30
905 public List<SequenceFeature> findOverlappingFeatures(int pos,
906 List<SequenceFeature> result)
910 result = new ArrayList<>();
913 if (contactFeatureStarts != null)
915 findContacts(contactFeatureStarts, pos, result, true);
916 findContacts(contactFeatureEnds, pos, result, false);
918 if (featuresList != null)
920 findOverlaps(featuresList, pos, result);
928 * contact features ordered by first contact position
930 private SequenceFeature[] orderedFeatureStarts;
932 private void rebuildArrays(int n)
934 if (startComp == null)
936 startComp = new StartComparator();
938 orderedFeatureStarts = new SequenceFeature[n];
939 for (int i = n; --i >= 0;)
941 SequenceFeature sf = featuresList.get(i);
942 sf.index = i; // for debugging only
943 orderedFeatureStarts[i] = sf;
945 Arrays.sort(orderedFeatureStarts, startComp);
946 linkFeatures(orderedFeatureStarts);
950 * just a standard Comparator
952 private static StartComparator startComp;
954 class StartComparator implements Comparator<SequenceFeature>
958 public int compare(SequenceFeature o1, SequenceFeature o2)
962 return (p1 < p2 ? -1 : p1 > p2 ? 1 : 0);
971 private void linkFeatures(SequenceFeature[] intervals)
973 if (intervals.length < 2)
977 int maxEnd = intervals[0].end;
978 for (int i = 1, n = intervals.length; i < n; i++)
980 SequenceFeature ithis = intervals[i];
981 if (ithis.begin <= maxEnd)
983 ithis.containedBy = getContainedBy(intervals[i - 1], ithis);
985 if (ithis.end > maxEnd)
993 * Since we are traversing the sorted feature array, all elements prior to the
994 * one we are working on have been fully linked. All we are doing is following
995 * those links until we find the first array feature with a containedBy
996 * element that has an end >= our begin point. It is generally a very short
997 * list -- maybe one or two depths. But it might be more than that.
1003 private SequenceFeature getContainedBy(SequenceFeature sf,
1004 SequenceFeature sf0)
1006 int begin = sf0.begin;
1009 if (begin <= sf.end)
1011 System.out.println("\nFS found " + sf0.index + ":" + sf0
1012 + "\nFS in " + sf.index + ":" + sf);
1015 sf = sf.containedBy;
1020 // Searching for overlapping features at a given position:
1023 * Binary search for contact start or end at a given (Overview) position.
1030 * @author Bob Hanson 2019.07.30
1032 private static void findContacts(List<SequenceFeature> l, int pos,
1033 List<SequenceFeature> result, boolean isStart)
1036 int high = l.size() - 1;
1039 int mid = (low + high) >>> 1;
1040 SequenceFeature f = l.get(mid);
1041 switch (Long.signum((isStart ? f.begin : f.end) - pos))
1052 // could be "5" in 12345556788 ?
1053 while (++mid <= high && (f = l.get(mid)) != null
1054 && (isStart ? f.begin : f.end) == pos)
1058 while (--m >= low && (f = l.get(m)) != null
1059 && (isStart ? f.begin : f.end) == pos)
1069 * Find all overlaps; special case when there is only one feature. The
1070 * required array of start-sorted SequenceFeature is created lazily.
1076 private void findOverlaps(List<SequenceFeature> features, int pos,
1077 List<SequenceFeature> result)
1079 int n = featuresList.size();
1082 checkOne(featuresList.get(0), pos, result);
1085 if (orderedFeatureStarts == null)
1090 // (1) Find the closest feature to this position.
1092 SequenceFeature sf = findClosestFeature(orderedFeatureStarts, pos);
1094 // (2) Traverse the containedBy field, checking for overlap.
1102 sf = sf.containedBy;
1107 * Quick check when we only have one feature.
1113 private void checkOne(SequenceFeature sf, int pos,
1114 List<SequenceFeature> result)
1116 if (sf.begin <= pos && sf.end >= pos)
1124 * A binary search identical to the one used for contact start/end, but here
1125 * we return the feature itself.
1131 private SequenceFeature findClosestFeature(SequenceFeature[] l, int pos)
1134 int high = l.length - 1;
1137 int mid = (low + high) >>> 1;
1138 SequenceFeature f = l[mid];
1139 switch (Long.signum(f.begin - pos))
1149 while (++mid <= high && l[mid].begin == pos)
1158 return (high < 0 || low >= l.length ? null : l[high]);