Просмотр исходного кода

refactor greedy string tiling hash functionality into separate class

Jan Wittler 4 лет назад
Родитель
Сommit
a882430eb7

+ 0 - 9
jplag.frontend-utils/src/main/java/de/jplag/Token.java

@@ -12,7 +12,6 @@ public abstract class Token {
     private String file;
 
     private boolean basecode = false;
-    private int hash = -1; // hash-value. set and used by main algorithm (GSTiling)
 
     protected int type;
 
@@ -111,10 +110,6 @@ public abstract class Token {
      */
     protected abstract String type2string();
 
-    /* package-private */ int getHash() {
-        return hash;
-    }
-
     /**
      * @return whether this token is part of a basecode.
      */
@@ -130,8 +125,4 @@ public abstract class Token {
     /* package-private */ void setFile(String file) {
         this.file = file;
     }
-
-    /* package-private */ void setHash(int hash) {
-        this.hash = hash;
-    }
 }

+ 0 - 77
jplag.frontend-utils/src/main/java/de/jplag/TokenHashMap.java

@@ -1,77 +0,0 @@
-package de.jplag;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A {@link HashMap} that maps Integer keys to multiple Integer values. Note that all keys with identical
- * <code>(key % prime)</code> are mapped to the same values. Specifically, <code>prime</code> is the next prime number
- * that is larger or equal to the specified size (see {@link TokenHashMap#TokenHashMap(int)}).
- */
-public class TokenHashMap {
-    private static final int CERTAINTY = 100;
-    private final Map<Integer, List<Integer>> mappedEntries;
-    private final int primeNumber;
-
-    /**
-     * Creates the {@link HashMap}.
-     * @param size specifies the initial size and the key mapping (see {@link TokenHashMap}).
-     */
-    public TokenHashMap(int size) {
-        mappedEntries = new HashMap<>(size);
-        primeNumber = nextPrimeNumber(size);
-    }
-
-    /**
-     * Returns all stored numbers for a key. Note that all keys with identical <code>(key % prime)</code> are mapped to the
-     * same values (see {@link TokenHashMap}).
-     * @param key is the specific key.
-     * @return the stored numbers or an empty list if nothing is stored.
-     */
-    public final List<Integer> get(int key) {
-        int actualKey = key % primeNumber;
-        if (mappedEntries.containsKey(actualKey)) {
-            return new ArrayList<>(mappedEntries.get(actualKey));
-        }
-        return Collections.emptyList();
-    }
-
-    /**
-     * Stores a number for a key, does not replace the previous stored numbers for that key. Note that all keys with
-     * identical <code>(key % prime)</code> are mapped to the same values (see {@link TokenHashMap}).
-     * @param key is the specific key.
-     * @param value is the number to store.
-     */
-    public final void put(int key, int value) {
-        int actualKey = key % primeNumber;
-        if (mappedEntries.containsKey(actualKey)) {
-            mappedEntries.get(actualKey).add(value);
-        } else {
-            List<Integer> entries = new ArrayList<>();
-            entries.add(value);
-            mappedEntries.put(actualKey, entries);
-        }
-    }
-
-    /**
-     * Calculates the next prime number (including 1) that is larger or equal to a given number.
-     * @param number is the give number.
-     * @return the next prime number.
-     */
-    private int nextPrimeNumber(int number) {
-        if (number <= 1) {
-            return 1;
-        }
-        for (int possiblePrime = number; possiblePrime < 2 * number; possiblePrime++) { // Bertrand's postulate
-            BigInteger bigInt = BigInteger.valueOf(possiblePrime);
-            if (bigInt.isProbablePrime(CERTAINTY)) {
-                return possiblePrime;
-            }
-        }
-        throw new IllegalStateException("Should never be reached because of Bertrand's postulate!");
-    }
-}

+ 9 - 5
jplag.frontend-utils/src/main/java/de/jplag/TokenList.java

@@ -3,15 +3,14 @@ package de.jplag;
 import static java.util.stream.Collectors.toList;
 
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 
 /**
- * List of tokens. Allows random access to individual tokens. Contains a hash map for token hashes.
+ * List of tokens. Allows random access to individual tokens.
  */
-public class TokenList {
+public class TokenList implements Iterable<Token> {
     private final List<Token> tokens;
-    TokenHashMap tokenHashes = null;
-    int hashLength = -1;
 
     /**
      * Creates an empty token list.
@@ -48,7 +47,7 @@ public class TokenList {
      * Returns a view on all tokens.
      * @return all tokens.
      */
-    public Iterable<Token> allTokens() {
+    public List<Token> allTokens() {
         return new ArrayList<>(tokens);
     }
 
@@ -74,4 +73,9 @@ public class TokenList {
             return "Token list to large for output: " + tokens.size() + " Tokens";
         }
     }
+
+    @Override
+    public Iterator<Token> iterator() {
+        return tokens.iterator();
+    }
 }

+ 18 - 62
jplag/src/main/java/de/jplag/GreedyStringTiling.java

@@ -4,8 +4,10 @@ import static de.jplag.TokenConstants.FILE_END;
 import static de.jplag.TokenConstants.SEPARATOR_TOKEN;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import de.jplag.options.JPlagOptions;
@@ -21,70 +23,19 @@ import de.jplag.options.JPlagOptions;
 public class GreedyStringTiling {
 
     private final JPlagOptions options;
+    private Map<Submission, SubsequenceHashLookupTable> hashLookupTables = new HashMap<>();
 
     public GreedyStringTiling(JPlagOptions options) {
         this.options = options;
     }
 
-    /**
-     * Creating hashes in linear time. The hash-code will be written in every Token for the next &lt;hashLength&gt; token
-     * (includes the Token itself).
-     * @param tokenList contains the tokens.
-     * @param markedTokens contains the marked tokens.
-     * @param hashLength is the hash length (condition: 1 &lt; hashLength &lt; 26)
-     */
-    public void createHashes(TokenList tokenList, Set<Token> markedTokens, int hashLength) {
-        // Here the upper boundary of the hash length is set.
-        // It is determined by the number of bits of the 'int' data type and the number of tokens.
-        if (hashLength < 1) {
-            hashLength = 1;
-        }
-        hashLength = (hashLength < 26 ? hashLength : 25);
-
-        if (tokenList.size() < hashLength) {
-            return;
-        }
-
-        int modulo = ((1 << 6) - 1);   // Modulo 64!
-
-        int loops = tokenList.size() - hashLength;
-        tokenList.tokenHashes = new TokenHashMap(3 * loops);
-        int hash = 0;
-        int hashedLength = 0;
-        for (int i = 0; i < hashLength; i++) {
-            hash = (2 * hash) + (tokenList.getToken(i).type & modulo);
-            hashedLength++;
-            if (markedTokens.contains(tokenList.getToken(i))) {
-                hashedLength = 0;
-            }
-        }
-        int factor = (hashLength != 1 ? (2 << (hashLength - 2)) : 1);
-
-        for (int i = 0; i < loops; i++) {
-            if (hashedLength >= hashLength) {
-                tokenList.getToken(i).setHash(hash);
-                tokenList.tokenHashes.put(hash, i);   // add into hashtable
-            } else {
-                tokenList.getToken(i).setHash(-1);
-            }
-            hash -= factor * (tokenList.getToken(i).type & modulo);
-            hash = (2 * hash) + (tokenList.getToken(i + hashLength).type & modulo);
-            if (markedTokens.contains(tokenList.getToken(i + hashLength))) {
-                hashedLength = 0;
-            } else {
-                hashedLength++;
-            }
-        }
-        tokenList.hashLength = hashLength;
-    }
-
     /**
      * Preprocesses the given base code submission.
      * Should be called before computing comparisons if there is a base code submission.
      * @param baseSubmission is the base code submission. Must not be null.
      */
     public void preprocessBaseCodeSubmission(Submission baseSubmission) {
-        createHashes(baseSubmission.getTokenList(), Set.of(), options.getMinimumTokenMatch());
+        subsequenceHashLookupTableForSubmission(baseSubmission, Set.of());
     }
 
     public final JPlagComparison compare(Submission firstSubmission, Submission secondSubmission) {
@@ -130,13 +81,8 @@ public class GreedyStringTiling {
         Set<Token> leftMarkedTokens = initiallyMarkedTokens(first, isBaseCodeComparison);
         Set<Token> rightMarkedTokens = initiallyMarkedTokens(second, isBaseCodeComparison);
 
-        // create hashes:
-        if (first.hashLength != minimumTokenMatch) {
-            createHashes(first, leftMarkedTokens, minimumTokenMatch); // don't make table if it is not a base code comparison
-        }
-        if (second.hashLength != minimumTokenMatch || second.tokenHashes == null) {
-            createHashes(second, rightMarkedTokens, minimumTokenMatch);
-        }
+        SubsequenceHashLookupTable leftLookupTable = subsequenceHashLookupTableForSubmission(firstSubmission, leftMarkedTokens);
+        SubsequenceHashLookupTable rightLookupTable = subsequenceHashLookupTableForSubmission(secondSubmission, rightMarkedTokens);
 
         List<Match> matches = new ArrayList<>();
 
@@ -146,10 +92,11 @@ public class GreedyStringTiling {
             maxMatch = minimumTokenMatch;
             matches.clear();
             for (int x = 0; x < first.size() - maxMatch; x++) {
-                if (leftMarkedTokens.contains(first.getToken(x)) || first.getToken(x).getHash() == -1) {
+                int leftSubsequenceHash = leftLookupTable.subsequenceHashForStartIndex(x);
+                if (leftMarkedTokens.contains(first.getToken(x)) || leftSubsequenceHash == SubsequenceHashLookupTable.NO_HASH) {
                     continue;
                 }
-                List<Integer> hashedTokens = second.tokenHashes.get(first.getToken(x).getHash());
+                List<Integer> hashedTokens = rightLookupTable.startIndexesOfPossiblyMatchingSubsequencesForSubsequenceHash(leftSubsequenceHash);
                 inner: for (Integer y : hashedTokens) {
                     if (rightMarkedTokens.contains(second.getToken(y)) || maxMatch >= second.size() - y) { // >= because of pivots!
                         continue;
@@ -218,4 +165,13 @@ public class GreedyStringTiling {
         }
         return markedTokens;
     }
+
+    private SubsequenceHashLookupTable subsequenceHashLookupTableForSubmission(Submission submission, Set<Token> markedTokens) {
+        if (hashLookupTables.containsKey(submission)) {
+            return hashLookupTables.get(submission);
+        }
+        SubsequenceHashLookupTable lookupTable = new SubsequenceHashLookupTable(options.getMinimumTokenMatch(), submission.getTokenList().allTokens(), markedTokens);
+        hashLookupTables.put(submission, lookupTable);
+        return lookupTable;
+    }
 }

+ 103 - 0
jplag/src/main/java/de/jplag/SubsequenceHashLookupTable.java

@@ -0,0 +1,103 @@
+package de.jplag;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class SubsequenceHashLookupTable {
+    private static final int MAX_HASH_LENGTH = 25;
+    private static final int TOKEN_HASH_MODULO = 63;
+
+    public static final int NO_HASH = -1;
+
+    private int windowSize;
+    private List<Token> tokens;
+    private int[] subsequenceHashes;
+    private Map<Integer, List<Integer>> hashTable;
+
+    public SubsequenceHashLookupTable(int windowSize, List<Token> tokens, Set<Token> markedTokens) {
+        windowSize = Math.max(1, windowSize);
+        windowSize = Math.min(MAX_HASH_LENGTH, windowSize);
+        this.windowSize = windowSize;
+        this.tokens = tokens;
+
+        if (tokens.size() < windowSize) {
+            return;
+        }
+
+        subsequenceHashes = new int[tokens.size() - windowSize];
+        hashTable = new HashMap<>(subsequenceHashes.length);
+        computeSubsequenceHashes(markedTokens);
+    }
+
+    public int getWindowSize() {
+        return windowSize;
+    }
+
+    public List<Token> getTokens() {
+        return tokens;
+    }
+
+    public int subsequenceHashForStartIndex(int startIndex) {
+        return subsequenceHashes[startIndex];
+    }
+
+    public List<Integer> startIndexesOfPossiblyMatchingSubsequencesForSubsequenceHash(int subsequenceHash) {
+        if (hashTable.containsKey(subsequenceHash)) {
+            return hashTable.get(subsequenceHash);
+        }
+        return List.of();
+    }
+
+    /**
+     * Creating hashes in linear time. The hash-code will be written in every Token for the next &lt;hashLength&gt; token
+     * (includes the Token itself).
+     * @param tokenList contains the tokens.
+     * @param markedTokens contains the marked tokens.
+     * @param hashLength is the hash length (condition: 1 &lt; hashLength &lt; 26)
+     */
+    private void computeSubsequenceHashes(Set<Token> markedTokens) {
+        int hash = 0;
+        int hashedLength = 0;
+        int factor = (windowSize != 1 ? (2 << (windowSize - 2)) : 1);
+
+        for (int windowEndIndex = 0; windowEndIndex < tokens.size(); windowEndIndex++) {
+            int windowStartIndex = windowEndIndex - windowSize;
+            if (windowStartIndex >= 0) {
+                if (hashedLength >= windowSize) {
+                    subsequenceHashes[windowStartIndex] = hash;
+                    addToHashTable(windowStartIndex, hash);
+                } else {
+                    subsequenceHashes[windowStartIndex] = NO_HASH;
+                }
+                //windowing to create hashes in linear time
+                // hash = sum over (j=0 to hashLength) with pow(2, hashLength-j-1) * hash(tokens[i+j])
+                hash -= factor * (hashValueForToken(tokens.get(windowStartIndex)));
+            }
+            
+            hash = (2 * hash) + (hashValueForToken(tokens.get(windowEndIndex)));
+            if (markedTokens.contains(tokens.get(windowEndIndex))) {
+                hashedLength = 0;
+            } else {
+                hashedLength++;
+            }
+        }
+    }
+
+    private int hashValueForToken(Token token) {
+        return token.type % TOKEN_HASH_MODULO;
+    }
+
+    private void addToHashTable(int startIndex, int subsequenceHash) {
+        if (hashTable.containsKey(subsequenceHash)) {
+            hashTable.get(subsequenceHash).add(startIndex);
+        }
+        else {
+            List<Integer> startIndexes = new  ArrayList<>();
+            startIndexes.add(startIndex);
+            hashTable.put(subsequenceHash, startIndexes);
+        }
+    }
+}