JAL-4241 add SeqsetUtils.filterSequence function
[jalview.git] / src / jalview / analysis / SeqsetUtils.java
index adb70e3..5420aff 100755 (executable)
@@ -30,6 +30,7 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 
 import java.util.ArrayList;
+import java.util.BitSet;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Hashtable;
@@ -40,6 +41,8 @@ import java.util.Optional;
 import java.util.Vector;
 import static java.lang.String.format;
 
+import java.nio.CharBuffer;
+
 public class SeqsetUtils
 {
   public static class SequenceInfo {
@@ -90,6 +93,32 @@ public class SeqsetUtils
   }
 
   /**
+   * Filter the sequence through the mask leaving only characters at positions
+   * where the mask value was true. The length of the resulting array is
+   * the cardinality of the mask from 0 to sequence length.
+   *
+   * @param sequence
+   *          input sequence
+   * @param mask
+   *          mask used to filter the sequence characters
+   * @return input array filtered through the mask
+   */
+  public static char[] filterSequence(char[] sequence, BitSet mask)
+  {
+    mask = mask.get(0, sequence.length);
+    char[] result = new char[mask.cardinality()];
+    for (int i = mask.nextSetBit(0), j = 0; i >= 0;)
+    {
+      result[j++] = sequence[i];
+      if (i == Integer.MAX_VALUE)
+        // prevents integer overflow of (i + 1)
+        break;
+      i = mask.nextSetBit(i + 1);
+    }
+    return result;
+  }
+
+  /**
    * Recover essential properties of a sequence from a hashtable TODO: replace
    * these methods with something more elegant.
    *