JAL-3383 JAL-3253-applet
[jalview.git] / src / jalview / datamodel / features / FeatureStore.java
index 716eb04..2cdbeb2 100644 (file)
@@ -23,27 +23,17 @@ package jalview.datamodel.features;
 import jalview.datamodel.SequenceFeature;
 
 import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
-import intervalstore.api.IntervalStoreI;
 import intervalstore.impl.BinarySearcher;
-import intervalstore.impl.IntervalStore;
 
-/**
- * A data store for a set of sequence features that supports efficient lookup of
- * features overlapping a given range. Intended for (but not limited to) storage
- * of features for one sequence and feature type.
- * 
- * @author gmcarstairs
- *
- */
-public class FeatureStore
+public abstract class FeatureStore implements FeatureStoreI
 {
+
   /*
    * Non-positional features have no (zero) start/end position.
    * Kept as a separate list in case this criterion changes in future.
@@ -64,7 +54,13 @@ public class FeatureStore
    * IntervalStore holds remaining features and provides efficient
    * query for features overlapping any given interval
    */
-  IntervalStoreI<SequenceFeature> features;
+  Collection<SequenceFeature> features;
+
+  @Override
+  public Collection<SequenceFeature> getFeatures()
+  {
+    return features;
+  }
 
   /*
    * Feature groups represented in stored positional features 
@@ -92,15 +88,11 @@ public class FeatureStore
 
   float nonPositionalMaxScore;
 
-  private ArrayList<SequenceFeature> featuresList;
-
   /**
    * Constructor
    */
   public FeatureStore()
   {
-    features = new IntervalStore<>();
-    featuresList = new ArrayList<>();
     positionalFeatureGroups = new HashSet<>();
     nonPositionalFeatureGroups = new HashSet<>();
     positionalMinScore = Float.NaN;
@@ -120,6 +112,7 @@ public class FeatureStore
    * @param feature
    */
 
+  @Override
   public boolean addFeature(SequenceFeature feature)
   {
     if (contains(feature))
@@ -184,6 +177,7 @@ public class FeatureStore
    * @param feature
    * @return
    */
+  @Override
   public boolean contains(SequenceFeature feature)
   {
     if (feature.isNonPositional())
@@ -194,8 +188,8 @@ public class FeatureStore
 
     if (feature.isContactFeature())
     {
-      return contactFeatureStarts == null ? false
-              : listContains(contactFeatureStarts, feature);
+      return contactFeatureStarts != null
+              && listContains(contactFeatureStarts, feature);
     }
 
     return features == null ? false : features.contains(feature);
@@ -250,14 +244,8 @@ public class FeatureStore
    */
   protected synchronized void addNestedFeature(SequenceFeature feature)
   {
-    if (features == null)
-    {
-      features = new IntervalStore<>();
-    }
     features.add(feature);
-    featuresList.add(feature);
   }
-
   /**
    * Add a contact feature to the lists that hold them ordered by start (first
    * contact) and by end (second contact) position, ensuring the lists remain
@@ -272,9 +260,6 @@ public class FeatureStore
     if (contactFeatureStarts == null)
     {
       contactFeatureStarts = new ArrayList<>();
-    }
-    if (contactFeatureEnds == null)
-    {
       contactFeatureEnds = new ArrayList<>();
     }
 
@@ -338,151 +323,8 @@ public class FeatureStore
     return false;
   }
 
-  /**
-   * Returns a (possibly empty) list of features whose extent overlaps the given
-   * range. The returned list is not ordered. Contact features are included if
-   * either of the contact points lies within the range.
-   * 
-   * @param start
-   *          start position of overlap range (inclusive)
-   * @param end
-   *          end position of overlap range (inclusive)
-   * @return
-   */
-
-  public List<SequenceFeature> findOverlappingFeatures(long start, long end)
-  {
-    List<SequenceFeature> result = new ArrayList<>();
-
-    findContactFeatures(start, end, result);
-
-    if (features != null)
-    {
-      result.addAll(features.findOverlaps(start, end));
-    }
-
-    return result;
-  }
-
-  /**
-   * Adds contact features to the result list where either the second or the
-   * first contact position lies within the target range
-   * 
-   * @param from
-   * @param to
-   * @param result
-   */
-  protected void findContactFeatures(long from, long to,
-          List<SequenceFeature> result)
-  {
-    if (contactFeatureStarts != null)
-    {
-      findContactStartOverlaps(from, to, result);
-    }
-    if (contactFeatureEnds != null)
-    {
-      findContactEndOverlaps(from, to, result);
-    }
-  }
-
-  /**
-   * Adds to the result list any contact features whose end (second contact
-   * point), but not start (first contact point), lies in the query from-to
-   * range
-   * 
-   * @param from
-   * @param to
-   * @param result
-   */
-  protected void findContactEndOverlaps(long from, long to,
-          List<SequenceFeature> result)
-  {
-    /*
-     * find the first contact feature (if any) 
-     * whose end point is not before the target range
-     */
-    int index = BinarySearcher.findFirst(contactFeatureEnds,
-            f -> f.getEnd() >= from);
-
-    while (index < contactFeatureEnds.size())
-    {
-      SequenceFeature sf = contactFeatureEnds.get(index);
-      if (!sf.isContactFeature())
-      {
-        System.err.println("Error! non-contact feature type " + sf.getType()
-                + " in contact features list");
-        index++;
-        continue;
-      }
-
-      int begin = sf.getBegin();
-      if (begin >= from && begin <= to)
-      {
-        /*
-         * this feature's first contact position lies in the search range
-         * so we don't include it in results a second time
-         */
-        index++;
-        continue;
-      }
-
-      if (sf.getEnd() > to)
-      {
-        /*
-         * this feature (and all following) has end point after the target range
-         */
-        break;
-      }
-
-      /*
-       * feature has end >= from and end <= to
-       * i.e. contact end point lies within overlap search range
-       */
-      result.add(sf);
-      index++;
-    }
-  }
-
-  /**
-   * Adds contact features whose start position lies in the from-to range to the
-   * result list
-   * 
-   * @param from
-   * @param to
-   * @param result
-   */
-  protected void findContactStartOverlaps(long from, long to,
-          List<SequenceFeature> result)
-  {
-    int index = BinarySearcher.findFirst(contactFeatureStarts,
-            f -> f.getBegin() >= from);
-
-    while (index < contactFeatureStarts.size())
-    {
-      SequenceFeature sf = contactFeatureStarts.get(index);
-      if (!sf.isContactFeature())
-      {
-        System.err.println("Error! non-contact feature " + sf.toString()
-                + " in contact features list");
-        index++;
-        continue;
-      }
-      if (sf.getBegin() > to)
-      {
-        /*
-         * this feature's start (and all following) follows the target range
-         */
-        break;
-      }
-
-      /*
-       * feature has begin >= from and begin <= to
-       * i.e. contact start point lies within overlap search range
-       */
-      result.add(sf);
-      index++;
-    }
-  }
+  abstract protected void findContactFeatures(long from, long to,
+          List<SequenceFeature> result);
 
   /**
    * Answers a list of all positional features stored, in no guaranteed order
@@ -490,9 +332,10 @@ public class FeatureStore
    * @return
    */
 
-  public List<SequenceFeature> getPositionalFeatures()
+  @Override
+  public List<SequenceFeature> getPositionalFeatures(
+          List<SequenceFeature> result)
   {
-    List<SequenceFeature> result = new ArrayList<>();
 
     /*
      * add any contact features - from the list by start position
@@ -520,13 +363,15 @@ public class FeatureStore
    * @return
    */
 
-  public List<SequenceFeature> getContactFeatures()
+  @Override
+  public List<SequenceFeature> getContactFeatures(
+          List<SequenceFeature> result)
   {
-    if (contactFeatureStarts == null)
+    if (contactFeatureStarts != null)
     {
-      return Collections.emptyList();
+      result.addAll(contactFeatureStarts);
     }
-    return new ArrayList<>(contactFeatureStarts);
+    return result;
   }
 
   /**
@@ -536,13 +381,15 @@ public class FeatureStore
    * @return
    */
 
-  public List<SequenceFeature> getNonPositionalFeatures()
+  @Override
+  public List<SequenceFeature> getNonPositionalFeatures(
+          List<SequenceFeature> result)
   {
-    if (nonPositionalFeatures == null)
+    if (nonPositionalFeatures != null)
     {
-      return Collections.emptyList();
+      result.addAll(nonPositionalFeatures);
     }
-    return new ArrayList<>(nonPositionalFeatures);
+    return result;
   }
 
   /**
@@ -554,6 +401,7 @@ public class FeatureStore
    * @param sf
    */
 
+  @Override
   public synchronized boolean delete(SequenceFeature sf)
   {
     boolean removed = false;
@@ -588,7 +436,6 @@ public class FeatureStore
     if (!removed && features != null)
     {
       removed = features.remove(sf);
-      featuresList.remove(sf);
     }
 
     if (removed)
@@ -616,18 +463,32 @@ public class FeatureStore
     /*
      * scan non-positional features for groups and scores
      */
-    for (SequenceFeature sf : getNonPositionalFeatures())
+    if (nonPositionalFeatures != null)
     {
-      nonPositionalFeatureGroups.add(sf.getFeatureGroup());
-      float score = sf.getScore();
-      nonPositionalMinScore = min(nonPositionalMinScore, score);
-      nonPositionalMaxScore = max(nonPositionalMaxScore, score);
+      for (SequenceFeature sf : nonPositionalFeatures)
+      {
+        nonPositionalFeatureGroups.add(sf.getFeatureGroup());
+        float score = sf.getScore();
+        nonPositionalMinScore = min(nonPositionalMinScore, score);
+        nonPositionalMaxScore = max(nonPositionalMaxScore, score);
+      }
     }
 
     /*
      * scan positional features for groups, scores and extents
      */
-    for (SequenceFeature sf : getPositionalFeatures())
+
+    rescanPositional(contactFeatureStarts);
+    rescanPositional(features);
+  }
+
+  private void rescanPositional(Collection<SequenceFeature> sfs)
+  {
+    if (sfs == null)
+    {
+      return;
+    }
+    for (SequenceFeature sf : sfs)
     {
       positionalFeatureGroups.add(sf.getFeatureGroup());
       float score = sf.getScore();
@@ -677,19 +538,21 @@ public class FeatureStore
     }
   }
 
+
   /**
    * Answers true if this store has no features, else false
    * 
    * @return
    */
 
+  @Override
   public boolean isEmpty()
   {
     boolean hasFeatures = (contactFeatureStarts != null
             && !contactFeatureStarts.isEmpty())
             || (nonPositionalFeatures != null
                     && !nonPositionalFeatures.isEmpty())
-            || (features != null && features.size() > 0);
+            || features.size() > 0;
 
     return !hasFeatures;
   }
@@ -703,6 +566,7 @@ public class FeatureStore
    * @return
    */
 
+  @Override
   public Set<String> getFeatureGroups(boolean positionalFeatures)
   {
     if (positionalFeatures)
@@ -718,37 +582,83 @@ public class FeatureStore
   }
 
   /**
-   * Answers the number of positional (or non-positional) features stored.
-   * Contact features count as 1.
+   * Answers a list of all either positional or non-positional features whose
+   * feature group matches the given group (which may be null)
    * 
    * @param positional
+   * @param group
    * @return
    */
 
-  public int getFeatureCount(boolean positional)
+  @Override
+  public List<SequenceFeature> getFeaturesForGroup(boolean positional,
+          String group)
   {
-    if (!positional)
+    List<SequenceFeature> result = new ArrayList<>();
+
+    /*
+     * if we know features don't include the target group, no need
+     * to inspect them for matches
+     */
+    if (positional && !positionalFeatureGroups.contains(group)
+            || !positional && !nonPositionalFeatureGroups.contains(group))
     {
-      return nonPositionalFeatures == null ? 0
-              : nonPositionalFeatures.size();
+      return result;
     }
 
-    int size = 0;
+    if (positional)
+    {
+      addFeaturesForGroup(group, contactFeatureStarts, result);
+      addFeaturesForGroup(group, features, result);
+    }
+    else
+    {
+      addFeaturesForGroup(group, nonPositionalFeatures, result);
+    }
+    return result;
+  }
 
-    if (contactFeatureStarts != null)
+  private void addFeaturesForGroup(String group,
+          Collection<SequenceFeature> sfs, List<SequenceFeature> result)
+  {
+    if (sfs == null)
+    {
+      return;
+    }
+    for (SequenceFeature sf : sfs)
     {
-      // note a contact feature (start/end) counts as one
-      size += contactFeatureStarts.size();
+      String featureGroup = sf.getFeatureGroup();
+      if (group == null && featureGroup == null
+              || group != null && group.equals(featureGroup))
+      {
+        result.add(sf);
+      }
     }
+  }
 
-    if (features != null)
+  /**
+   * Answers the number of positional (or non-positional) features stored.
+   * Contact features count as 1.
+   * 
+   * @param positional
+   * @return
+   */
+
+  @Override
+  public int getFeatureCount(boolean positional)
+  {
+    if (!positional)
     {
-      size += features.size();
+      return nonPositionalFeatures == null ? 0
+              : nonPositionalFeatures.size();
     }
 
-    return size;
+    return (contactFeatureStarts == null ? 0 : contactFeatureStarts.size())
+            + features.size();
+
   }
 
+
   /**
    * Answers the total length of positional features (or zero if there are
    * none). Contact features contribute a value of 1 to the total.
@@ -756,6 +666,7 @@ public class FeatureStore
    * @return
    */
 
+  @Override
   public int getTotalFeatureLength()
   {
     return totalExtent;
@@ -770,6 +681,7 @@ public class FeatureStore
    * @return
    */
 
+  @Override
   public float getMinimumScore(boolean positional)
   {
     return positional ? positionalMinScore : nonPositionalMinScore;
@@ -784,48 +696,12 @@ public class FeatureStore
    * @return
    */
 
+  @Override
   public float getMaximumScore(boolean positional)
   {
     return positional ? positionalMaxScore : nonPositionalMaxScore;
   }
 
-  /**
-   * Answers a list of all either positional or non-positional features whose
-   * feature group matches the given group (which may be null)
-   * 
-   * @param positional
-   * @param group
-   * @return
-   */
-
-  public List<SequenceFeature> getFeaturesForGroup(boolean positional,
-          String group)
-  {
-    List<SequenceFeature> result = new ArrayList<>();
-
-    /*
-     * if we know features don't include the target group, no need
-     * to inspect them for matches
-     */
-    if (positional && !positionalFeatureGroups.contains(group)
-            || !positional && !nonPositionalFeatureGroups.contains(group))
-    {
-      return result;
-    }
-
-    List<SequenceFeature> sfs = positional ? getPositionalFeatures()
-            : getNonPositionalFeatures();
-    for (SequenceFeature sf : sfs)
-    {
-      String featureGroup = sf.getFeatureGroup();
-      if (group == null && featureGroup == null
-              || group != null && group.equals(featureGroup))
-      {
-        result.add(sf);
-      }
-    }
-    return result;
-  }
 
   /**
    * Adds the shift amount to the start and end of all positional features whose
@@ -837,6 +713,7 @@ public class FeatureStore
    * @return
    */
 
+  @Override
   public synchronized boolean shiftFeatures(int fromPosition, int shiftBy)
   {
     /*
@@ -869,301 +746,29 @@ public class FeatureStore
     return modified;
   }
 
-  /////////////////////// added by Bob Hanson ///////////////////////
-
-  // The following methods use a linked list of containment in features
-  // rather than IntervalStore. Implemented only for OverviewPanel, because
-  // only that makes calls for start == end in feature overlap requests.
-  //
-  //
-  // There are two parts --- initialization, and overlap searching.
-  //
-  // Initialization involves two steps:
-  //
-  // (1) sorting of features by start position using a standard Array.sort with
-  // Comparator.
-  // (2) linking of features, effectively nesting them.
-  //
-  // Searching also involves two steps:
-  //
-  // (1) binary search for a position within the sorted features array.
-  // (2) traversing the linked lists with an end check to read out the
-  // overlapped features at this position.
-  //
-  // All of this is done with very simple standard methods.
-
-  // single public method:
-
-  /**
-   * Find all features containing this position.
-   * 
-   * @param pos
-   * @return list of SequenceFeatures
-   * @author Bob Hanson 2019.07.30
-   */
-
-  public List<SequenceFeature> findOverlappingFeatures(int pos,
-          List<SequenceFeature> result)
-  {
-    if (result == null)
-    {
-      result = new ArrayList<>();
-    }
-
-    if (contactFeatureStarts != null)
-    {
-      findContacts(contactFeatureStarts, pos, result, true);
-      findContacts(contactFeatureEnds, pos, result, false);
-    }
-    if (featuresList != null)
-    {
-      findOverlaps(featuresList, pos, result);
-    }
-    return result;
-  }
-
-  // Initialization
-
-  /*
-   * contact features ordered by first contact position
-   */
-  private SequenceFeature[] orderedFeatureStarts;
-
-  private void rebuildArrays(int n)
-  {
-    if (startComp == null)
-    {
-      startComp = new StartComparator();
-    }
-    orderedFeatureStarts = new SequenceFeature[n];
-    for (int i = n; --i >= 0;)
-    {
-      SequenceFeature sf = featuresList.get(i);
-      sf.index = i; // for debugging only
-      orderedFeatureStarts[i] = sf;
-    }
-    Arrays.sort(orderedFeatureStarts, startComp);
-    linkFeatures(orderedFeatureStarts);
-  }
-
-  /**
-   * just a standard Comparator
-   */
-  private static StartComparator startComp;
-
-  class StartComparator implements Comparator<SequenceFeature>
-  {
-
-    @Override
-    public int compare(SequenceFeature o1, SequenceFeature o2)
-    {
-      int p1 = o1.begin;
-      int p2 = o2.begin;
-      return (p1 < p2 ? -1 : p1 > p2 ? 1 : 0);
-    }
-
-  }
-
-  /**
-   * Run through the sorted sequence array once, building the containedBy linked
-   * list references. Does a check first to make sure there is actually
-   * something out there that is overlapping. A null for sf.containedBy means
-   * there are no overlaps for this feature.
-   * 
-   * @param intervals
-   */
-  private void linkFeatures(SequenceFeature[] intervals)
-  {
-    if (intervals.length < 2)
-    {
-      return;
-    }
-    int maxEnd = intervals[0].end;
-    for (int i = 1, n = intervals.length; i < n; i++)
-    {
-      SequenceFeature sf = intervals[i];
-      if (sf.begin <= maxEnd)
-      {
-        sf.containedBy = getContainedBy(intervals[i - 1], sf);
-      }
-      if (sf.end > maxEnd)
-      {
-        maxEnd = sf.end;
-      }
-    }
-  }
-
-  /**
-   * Since we are traversing the sorted feature array in a forward direction,
-   * all elements prior to the one we are working on have been fully linked. All
-   * we are doing is following those links until we find the first array feature
-   * with a containedBy element that has an end &gt;= our begin point. It is
-   * generally a very short list -- maybe one or two depths. But it might be
-   * more than that.
-   * 
-   * @param sf
-   * @param sf0
-   * @return
-   */
-  private SequenceFeature getContainedBy(SequenceFeature sf,
-          SequenceFeature sf0)
-  {
-    int begin = sf0.begin;
-    while (sf != null)
-    {
-      if (begin <= sf.end)
-      {
-        System.out.println("\nFS found " + sf0.index + ":" + sf0
-                + "\nFS in    " + sf.index + ":" + sf);
-        return sf;
-      }
-      sf = sf.containedBy;
-    }
-    return null;
-  }
-
-  // search-stage methods
 
-  /**
-   * Binary search for contact start or end at a given (Overview) position.
-   * 
-   * @param l
-   * @param pos
-   * @param result
-   * @param isStart
-   * 
-   * @author Bob Hanson 2019.07.30
-   */
-  private static void findContacts(List<SequenceFeature> l, int pos,
-          List<SequenceFeature> result, boolean isStart)
+  @Override
+  public List<SequenceFeature> findOverlappingFeatures(long start, long end)
   {
-    int low = 0;
-    int high = l.size() - 1;
-    while (low <= high)
-    {
-      int mid = (low + high) >>> 1;
-      SequenceFeature f = l.get(mid);
-      switch (Long.signum((isStart ? f.begin : f.end) - pos))
-      {
-      case -1:
-        low = mid + 1;
-        continue;
-      case 1:
-        high = mid - 1;
-        continue;
-      case 0:
-        int m = mid;
-        result.add(f);
-        // could be "5" in 12345556788 ?
-        while (++mid <= high && (f = l.get(mid)) != null
-                && (isStart ? f.begin : f.end) == pos)
-        {
-          result.add(f);
-        }
-        while (--m >= low && (f = l.get(m)) != null
-                && (isStart ? f.begin : f.end) == pos)
-        {
-          result.add(f);
-        }
-        return;
-      }
-    }
+    return findOverlappingFeatures(start, end, null);
   }
 
-  /**
-   * Find all overlaps; special case when there is only one feature. The
-   * required array of start-sorted SequenceFeature is created lazily.
-   * 
-   * @param features
-   * @param pos
-   * @param result
-   */
-  private void findOverlaps(List<SequenceFeature> features, int pos,
-          List<SequenceFeature> result)
+  @Override
+  public List<SequenceFeature> getPositionalFeatures()
   {
-    int n = featuresList.size();
-    if (n == 1)
-    {
-      checkOne(featuresList.get(0), pos, result);
-      return;
-    }
-    if (orderedFeatureStarts == null)
-    {
-      rebuildArrays(n);
-    }
-
-    // (1) Find the closest feature to this position.
-
-    SequenceFeature sf = findClosestFeature(orderedFeatureStarts, pos);
-
-    // (2) Traverse the containedBy field, checking for overlap.
-
-    while (sf != null)
-    {
-      if (sf.end >= pos)
-      {
-        result.add(sf);
-      }
-      sf = sf.containedBy;
-    }
+    return getPositionalFeatures(new ArrayList<>());
   }
 
-  /**
-   * Quick check when we only have one feature.
-   * 
-   * @param sf
-   * @param pos
-   * @param result
-   */
-  private void checkOne(SequenceFeature sf, int pos,
-          List<SequenceFeature> result)
+  @Override
+  public List<SequenceFeature> getContactFeatures()
   {
-    if (sf.begin <= pos && sf.end >= pos)
-    {
-      result.add(sf);
-    }
-    return;
+    return getContactFeatures(new ArrayList<>());
   }
 
-  /**
-   * A binary search identical to the one used for contact start/end, but here
-   * we return the feature itself. Unlike Collection.BinarySearch, all we have
-   * to be is close, not exact, and we make sure if there is a string of
-   * identical starts, then we slide to the end so that we can check all of
-   * them.
-   * 
-   * @param l
-   * @param pos
-   * @return
-   */
-  private SequenceFeature findClosestFeature(SequenceFeature[] l, int pos)
+  @Override
+  public List<SequenceFeature> getNonPositionalFeatures()
   {
-    int low = 0;
-    int high = l.length - 1;
-    while (low <= high)
-    {
-      int mid = (low + high) >>> 1;
-      SequenceFeature f = l[mid];
-      switch (Long.signum(f.begin - pos))
-      {
-      case -1:
-        low = mid + 1;
-        continue;
-      case 1:
-        high = mid - 1;
-        continue;
-      case 0:
-
-        while (++mid <= high && l[mid].begin == pos)
-        {
-          ;
-        }
-        return l[--mid];
-      }
-    }
-    // -1 here?
-    return (high < 0 || low >= l.length ? null : l[high]);
+    return getNonPositionalFeatures(new ArrayList<>());
   }
 
-
 }