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

Clustering with pseudonymized reports

Simon Ding 4 лет назад
Родитель
Сommit
e8f91f85c5
30 измененных файлов с 2968 добавлено и 2 удалено
  1. 3 0
      .gitmodules
  2. 11 0
      jplag.frontend.scheme/.project
  3. 29 0
      jplag/pom.xml
  4. 5 0
      jplag/src/main/java/de/jplag/JPlag.java
  5. 15 0
      jplag/src/main/java/de/jplag/JPlagComparison.java
  6. 12 0
      jplag/src/main/java/de/jplag/JPlagResult.java
  7. 5 0
      jplag/src/main/java/de/jplag/clustering/Algorithms.java
  8. 81 0
      jplag/src/main/java/de/jplag/clustering/ClusteringAdapter.java
  9. 99 0
      jplag/src/main/java/de/jplag/clustering/ClusteringFactory.java
  10. 158 0
      jplag/src/main/java/de/jplag/clustering/ClusteringResult.java
  11. 72 0
      jplag/src/main/java/de/jplag/clustering/IntegerClusteringResult.java
  12. 46 0
      jplag/src/main/java/de/jplag/clustering/IntegerMapping.java
  13. 59 0
      jplag/src/main/java/de/jplag/clustering/Preprocessor.java
  14. 5 0
      jplag/src/main/java/de/jplag/clustering/Preprocessors.java
  15. 878 0
      jplag/src/main/java/de/jplag/clustering/algorithm/BFGS.java
  16. 188 0
      jplag/src/main/java/de/jplag/clustering/algorithm/BayesianOptimization.java
  17. 9 0
      jplag/src/main/java/de/jplag/clustering/algorithm/ClusteringAlgorithm.java
  18. 204 0
      jplag/src/main/java/de/jplag/clustering/algorithm/GaussianProcess.java
  19. 46 0
      jplag/src/main/java/de/jplag/clustering/algorithm/Histogram.java
  20. 163 0
      jplag/src/main/java/de/jplag/clustering/algorithm/SpectralClustering.java
  21. 186 0
      jplag/src/main/java/de/jplag/clustering/algorithm/TopDownHierarchicalClustering.java
  22. 55 0
      jplag/src/main/java/de/jplag/clustering/preprocessors/CdfPreprocessor.java
  23. 50 0
      jplag/src/main/java/de/jplag/clustering/preprocessors/PercentileThresholdProcessor.java
  24. 38 0
      jplag/src/main/java/de/jplag/clustering/preprocessors/ThresholdPreprocessor.java
  25. 194 0
      jplag/src/main/java/de/jplag/options/JPlagOptions.java
  26. 8 2
      jplag/src/main/java/de/jplag/options/SimilarityMetric.java
  27. 257 0
      jplag/src/test/java/de/jplag/clustering/ClusteringTest.java
  28. 37 0
      jplag/src/test/java/de/jplag/clustering/algorithm/GaussianProcessTest.java
  29. 54 0
      jplag/src/test/java/de/jplag/clustering/algorithm/TopDownHierarchicalClusteringTest.java
  30. 1 0
      jplag/src/test/resources/de/jplag/PseudonymizedReports

+ 3 - 0
.gitmodules

@@ -0,0 +1,3 @@
+[submodule "jplag/src/test/resources/de/jplag/PseudonymizedReports"]
+	path = jplag/src/test/resources/de/jplag/PseudonymizedReports
+	url = https://github.com/jplag/PseudonymizedReports

+ 11 - 0
jplag.frontend.scheme/.project

@@ -20,4 +20,15 @@
 		<nature>org.eclipse.m2e.core.maven2Nature</nature>
 		<nature>org.eclipse.jdt.core.javanature</nature>
 	</natures>
+	<filteredResources>
+		<filter>
+			<id>1636027862864</id>
+			<name></name>
+			<type>30</type>
+			<matcher>
+				<id>org.eclipse.core.resources.regexFilterMatcher</id>
+				<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
+			</matcher>
+		</filter>
+	</filteredResources>
 </projectDescription>

+ 29 - 0
jplag/pom.xml

@@ -217,5 +217,34 @@
       <scope>test</scope>
       <version>1.19.0</version>
     </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-math3</artifactId>
+      <version>3.6.1</version>
+    </dependency>
+    <dependency>
+      <groupId>com.github.haifengl</groupId>
+      <artifactId>smile-core</artifactId>
+      <version>2.6.0</version>
+    </dependency>
+    <dependency>
+    <groupId>org.bytedeco</groupId>
+    <artifactId>arpack-ng</artifactId>
+    <version>3.7.0-1.5.3</version>
+</dependency>
+    <dependency>
+      <!-- This needed by smile -->
+      <groupId>org.bytedeco</groupId>
+      <artifactId>openblas</artifactId>
+      <version>0.3.9-1.5.3</version>
+    </dependency>
+
+
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-core</artifactId>
+      <version>4.0.0</version>
+      <scope>test</scope>
+  </dependency>
   </dependencies>
 </project>

+ 5 - 0
jplag/src/main/java/de/jplag/JPlag.java

@@ -16,6 +16,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.stream.Collectors;
 
+import de.jplag.clustering.ClusteringFactory;
 import de.jplag.options.JPlagOptions;
 import de.jplag.options.LanguageOption;
 import de.jplag.options.Verbosity;
@@ -85,6 +86,10 @@ public class JPlag implements Program {
         errorVector = null; // errorVector is not needed anymore
         JPlagResult result = comparisonStrategy.compareSubmissions(submissions, baseCodeSubmission);
         printComparisonDuration(result.getDuration());
+
+        // 4. Do clustering
+        result.setClusteringResult(ClusteringFactory.getClusterings(result.getComparisons(), options));
+        
         return result;
     }
 

+ 15 - 0
jplag/src/main/java/de/jplag/JPlagComparison.java

@@ -222,6 +222,21 @@ public class JPlagComparison implements Comparator<JPlagComparison> { // FIXME T
         return ((int) (similarity() * ROUNDING_FACTOR)) / (float) ROUNDING_FACTOR;
     }
 
+    /**
+     * @param submission Either the first of second submission of this comparison.
+     * 
+     * @return Number of non EOF tokens int the submission, excluding base code matches.
+     */
+    public final int getNumberOfCountingTokens(Submission submission) {
+        int numberOfTokens = submission.getNumberOfTokens() - submission.getFiles().size();
+        if (submission == firstSubmission && firstBaseCodeMatches != null) {
+            numberOfTokens -= firstBaseCodeMatches.getNumberOfMatchedTokens();
+        } else if (submission == secondSubmission && secondBaseCodeMatches != null) {
+            numberOfTokens -= secondBaseCodeMatches.getNumberOfMatchedTokens();
+        }
+        return numberOfTokens;
+    }
+
     /**
      * @return Similarity of the first submission to the basecode in percent rounded down to the nearest tenth.
      */

+ 12 - 0
jplag/src/main/java/de/jplag/JPlagResult.java

@@ -1,7 +1,9 @@
 package de.jplag;
 
+import java.util.ArrayList;
 import java.util.List;
 
+import de.jplag.clustering.ClusteringResult;
 import de.jplag.options.JPlagOptions;
 
 /**
@@ -40,6 +42,8 @@ public class JPlagResult {
      */
     private int[] similarityDistribution = null;
 
+    private List<ClusteringResult<Submission>> clusteringResult = new ArrayList<>(0);
+
     /**
      * Creates empty results.
      */
@@ -65,6 +69,10 @@ public class JPlagResult {
         this.comparisons = this.getComparisons(limit);
     }
 
+    public void setClusteringResult(List<ClusteringResult<Submission>> clustering) {
+        this.clusteringResult = clustering;
+    }
+
     /**
      * @return a list of all comparisons sorted by percentage (descending)
      */
@@ -103,6 +111,10 @@ public class JPlagResult {
         return similarityDistribution;
     }
 
+    public List<ClusteringResult<Submission>> getClusteringResult() {
+        return this.clusteringResult;
+    }
+
     @Override
     public String toString() {
         return String.format("JPlagResult { comparisons: %d, duration: %d ms, language: %s, submissions: %d }", getComparisons().size(),

+ 5 - 0
jplag/src/main/java/de/jplag/clustering/Algorithms.java

@@ -0,0 +1,5 @@
+package de.jplag.clustering;
+
+public enum Algorithms {
+    AGGLOMERATIVE, SPECTRAL
+}

+ 81 - 0
jplag/src/main/java/de/jplag/clustering/ClusteringAdapter.java

@@ -0,0 +1,81 @@
+package de.jplag.clustering;
+
+import java.util.Collection;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+
+import de.jplag.JPlagComparison;
+import de.jplag.Submission;
+import de.jplag.clustering.algorithm.ClusteringAlgorithm;
+
+/**
+ * This class acts as an adapter between
+ * <ul>
+ *  <li>the clustering algorithms (that operate on collections of integers)</li>
+ *  <li>and the rest of the code base (that operates on {@link ClusteringResult}s of {@link Submission}s)</li>
+ * </ul>
+ */
+public class ClusteringAdapter {
+
+    private RealMatrix similarityMatrix;
+    private IntegerMapping<Submission> mapping;
+    
+    public ClusteringAdapter(Collection<JPlagComparison> comparisons, Function<JPlagComparison, Float> metric) {
+        mapping = new IntegerMapping<>(comparisons.size());
+        for (JPlagComparison comparison : comparisons) {
+            mapping.map(comparison.getFirstSubmission());
+            mapping.map(comparison.getSecondSubmission());
+        }
+        int size = mapping.size();
+
+        similarityMatrix = new Array2DRowRealMatrix(size, size);
+        for (JPlagComparison comparison : comparisons) {
+            int firstIndex = mapping.map(comparison.getFirstSubmission());
+            int secondIndex = mapping.map(comparison.getSecondSubmission());
+            float similarity = metric.apply(comparison);
+            similarityMatrix.setEntry(firstIndex, secondIndex, similarity);
+            similarityMatrix.setEntry(secondIndex, firstIndex, similarity);
+        }
+    }
+
+    public ClusteringResult<Submission> doClustering(ClusteringAlgorithm algorithm) {
+        Collection<Collection<Integer>> intResult = algorithm.cluster(similarityMatrix);
+        ClusteringResult<Integer> modularityClusterResult = new IntegerClusteringResult(intResult, similarityMatrix);
+        return new MappedClusteringResult<>(modularityClusterResult, mapping::unmap);
+    }
+
+    private static class MappedClusteringResult<M, T> implements ClusteringResult<T> {
+
+        private Collection<Cluster<T>> clusters;
+        private float communityStrength;
+        private int size;
+
+        public MappedClusteringResult(ClusteringResult<M> unmapped, Function<M, T> mapping) {
+            communityStrength = unmapped.getCommunityStrength();
+            clusters = unmapped.getClusters().stream().map(unmappedCluster -> {
+                return new ClusteringResult.DefaultCluster<T>(unmappedCluster.getMembers().stream().map(mapping).collect(Collectors.toList()), unmappedCluster.getCommunityStrength(), this);
+            }).collect(Collectors.toList());
+            size = unmapped.size();
+        }
+
+        @Override
+        public Collection<Cluster<T>> getClusters() {
+            return clusters;
+        }
+
+        @Override
+        public float getCommunityStrength() {
+            return communityStrength;
+        }
+
+        @Override
+        public int size() {
+            return size;
+        }
+
+    } 
+}
+ 

+ 99 - 0
jplag/src/main/java/de/jplag/clustering/ClusteringFactory.java

@@ -0,0 +1,99 @@
+package de.jplag.clustering;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import de.jplag.JPlagComparison;
+import de.jplag.Submission;
+import de.jplag.clustering.algorithm.ClusteringAlgorithm;
+import de.jplag.clustering.algorithm.SpectralClustering;
+import de.jplag.clustering.algorithm.TopDownHierarchicalClustering;
+import de.jplag.clustering.preprocessors.CdfPreprocessor;
+import de.jplag.clustering.preprocessors.PercentileThresholdProcessor;
+import de.jplag.clustering.preprocessors.ThresholdPreprocessor;
+import de.jplag.options.JPlagOptions;
+
+/**
+ * Produces the clustering according to the options.
+ */
+public class ClusteringFactory {
+    public static List<ClusteringResult<Submission>> getClusterings(Collection<JPlagComparison> comparisons, JPlagOptions options) {
+        if (!options.isClustering()) return Collections.emptyList();
+
+        // init algorithm
+        ClusteringAlgorithm ca = null;
+        if (options.getClusteringAlgorithm() == Algorithms.AGGLOMERATIVE) {
+            TopDownHierarchicalClustering.ClusteringOptions clusteringOptions = new TopDownHierarchicalClustering.ClusteringOptions();
+            clusteringOptions.minimalSimilarity = options.getClusteringAgglomerativeThreshold();
+            clusteringOptions.similarity = options.getClusteringAgglomerativeInterClusterSimilarity();
+            ca = new TopDownHierarchicalClustering(clusteringOptions);
+        } else if (options.getClusteringAlgorithm() == Algorithms.SPECTRAL) {
+            SpectralClustering.ClusteringOptions clusteringOptions = new SpectralClustering.ClusteringOptions();
+            clusteringOptions.GPVariance = options.getClusteringSpectralGPVariance();
+            clusteringOptions.kernelBandwidth = options.getClusteringSpectralKernelBandwidth();
+            clusteringOptions.maxKMeansIterations = options.getClusteringSpectralMaxKMeansIterationPerRun();
+            clusteringOptions.maxRuns = options.getClusteringSpectralMaxRuns();
+            clusteringOptions.minRuns = options.getClusteringSpectralMinRuns();
+            ca = new SpectralClustering(clusteringOptions);
+        }
+
+        // init preprocessor
+        Preprocessor preprocessor;
+        switch (options.getClusteringPreprocessor()) {
+            case CDF:
+                preprocessor = new CdfPreprocessor();
+                break;
+            case THRESHOLD:
+                preprocessor = new ThresholdPreprocessor(options.getClusteringPreprocessorThreshold());
+                break;
+            case PERCENTILE:
+                preprocessor = new PercentileThresholdProcessor(options.getClusteringPreprocessorPercentile());
+                break;
+            case NONE:
+            default:
+                preprocessor = null;
+                break;
+        }
+        if (preprocessor != null) {
+            // Package preprocessor into a clustering algorithm
+            ca = new Preprocessor.PreprocessedClusteringAlgorithm(ca, preprocessor);
+        }
+
+        // init adapter
+        ClusteringAdapter adapter = new ClusteringAdapter(comparisons, options.getClusteringSimilarityMetric());
+
+        // run clustering
+        ClusteringResult<Submission> result = adapter.doClustering(ca);
+
+        // remove bad clusters
+        if (options.isClusteringPruneBadClusters()) {
+            result = removeBadClusters(result);
+        }
+        return List.of(result);
+    }
+
+    private static ClusteringResult<Submission> removeBadClusters(final ClusteringResult<Submission> clustering) {
+        return new ClusteringResult<>() {
+
+            @Override
+            public Collection<Cluster<Submission>> getClusters() {
+                return clustering.getClusters().stream()
+                    .filter(cluster -> !cluster.isBadCluster())
+                    .collect(Collectors.toList());
+            }
+
+            @Override
+            public float getCommunityStrength() {
+                // Do not lie by letting the clustering improve by wiping away the bad part...
+                return clustering.getCommunityStrength();
+            }
+
+            @Override
+            public int size() {
+                return getClusters().size();
+            }
+        };
+    }
+}

+ 158 - 0
jplag/src/main/java/de/jplag/clustering/ClusteringResult.java

@@ -0,0 +1,158 @@
+package de.jplag.clustering;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+public interface ClusteringResult<T> {
+
+    Collection<Cluster<T>> getClusters();
+
+    /**
+     * Community strength of the clustering.
+     * 
+     * The expectation of community strength in a random graph is zero and it can not exceed one.
+     * It's the sum of it's clusters {@link Cluster#getCommunityStrength}.  
+     * 
+     * If the underlying network is not changed, a higher community strength denotes a better clustering.
+     * 
+     * <p>
+     * See:
+     * Finding and evaluating community structure in networks,
+     * M. E. J. Newman and M. Girvan,
+     * Phys. Rev. E 69, 026113 – Published 26 February 2004,
+     * Doi: 10.1103/PhysRevE.69.026113
+     * </p>
+     * 
+     * It's called modularity in that paper.
+     * @param clustering
+     * @param similarity
+     * @return
+     */
+    float getCommunityStrength();
+
+    int size();
+
+    default float getWorth(BiFunction<T, T, Float> similarity) {
+        return (float) getClusters().stream()
+            .mapToDouble(c -> c.getWorth(similarity))
+            .map(worth -> Double.isFinite(worth) ? worth : 0)
+            .average()
+            .getAsDouble();
+    }
+    
+    public interface Cluster<T> {
+        Collection<T> getMembers();
+
+        /**
+         * See {@link ClusteringResult#getCommunityStrength}
+         * @return community strength of the cluster
+         */
+        float getCommunityStrength();
+
+        ClusteringResult<T> getClusteringResult();
+
+        /**
+         * @return How much each member o f this cluster contributes to the {@link ClusteringResult#getCommunityStrength} 
+         */
+        default float getCommunityStrengthPerConnection() {
+            int size = getMembers().size();
+            if (size < 2) return 0;
+            return getCommunityStrength() / connections();
+        }
+
+        /**
+         * Computes a normalized community strength per connection.
+         * Can be used as measure for strength of evidence in comparison to other clusters in the same clustering.
+         * Guaranteed to be smaller than 1.
+         * Negative values indicate non-clusters.
+         * 
+         * @return normalized community strength per connection
+         */
+        default float getNormalizedCommunityStrengthPerConnection() {
+            List<Cluster<T>> goodClusters = getClusteringResult().getClusters().stream().filter(cluster -> cluster.getCommunityStrength() > 0).collect(Collectors.toList());
+            float posCommunityStrengthSum = (float) goodClusters.stream().mapToDouble(Cluster::getCommunityStrengthPerConnection).sum();
+
+            int size = getClusteringResult().size();
+            if (size < 2) return getCommunityStrengthPerConnection();
+            return getCommunityStrengthPerConnection() / posCommunityStrengthSum;
+        }
+
+        /**
+         * How much this cluster is worth during optimization.
+         */
+        default double getWorth(BiFunction<T, T, Float> similarity) {
+            double ncs = getCommunityStrength();
+            if (getMembers().size() > 1) {
+                ncs /= connections();
+            }
+            double avgSim = avgSimilarity(similarity);
+            return ncs * avgSim;
+        }
+
+        /**
+         * Computes the average similarity inside the cluster.
+         * 
+         * @param similarity function that supplies the similarity of two cluster members.
+         * @return average similarity
+         */
+        default float avgSimilarity(BiFunction<T, T, Float> similarity) {
+            List<T> members = new ArrayList<>(getMembers());
+            if (members.size() < 2) {
+                return 1;
+            }
+            float similaritySum = 0;
+            for (int i = 0; i < members.size(); i++) {
+                for (int j = i + 1; j < members.size(); j++) {
+                    similaritySum += similarity.apply(members.get(i), members.get(j));
+                }
+            }
+            return similaritySum / connections();
+        }
+
+        default int connections() {
+            int size = getMembers().size();
+            return ((size - 1) * size) / 2;
+        }
+
+        default boolean isBadCluster() {
+            return getMembers().size() < 2 || getCommunityStrength() < 0;
+        }
+    }
+
+
+    public static class DefaultCluster<T> implements Cluster<T> {
+
+        private float communityStrength;
+        private Collection<T> members;
+        private ClusteringResult<T> clusteringResult;
+
+        public DefaultCluster(Collection<T> members, float communityStrength, ClusteringResult<T> clustering) {
+            this.members = new ArrayList<>(members);
+            this.communityStrength = communityStrength;
+            this.clusteringResult = clustering;
+        }
+
+        @Override
+        public Collection<T> getMembers() {
+            return members;
+        }
+
+        @Override
+        public float getCommunityStrength() {
+            return communityStrength;
+        }
+
+        @Override
+        public ClusteringResult<T> getClusteringResult() {
+            return clusteringResult;
+        }
+
+
+
+    } 
+}
+
+

+ 72 - 0
jplag/src/main/java/de/jplag/clustering/IntegerClusteringResult.java

@@ -0,0 +1,72 @@
+package de.jplag.clustering;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.DoubleStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+
+public class IntegerClusteringResult implements ClusteringResult<Integer> {
+
+    private Collection<Cluster<Integer>> clusters = new ArrayList<>();
+    private double communityStrength = 0;
+    private int size;
+
+    /**
+     * Responsible for calculating {@link ClusteringResult#getCommunityStrength}
+     */
+    public IntegerClusteringResult(Collection<Collection<Integer>> clustering, RealMatrix similarity) {
+        int N = similarity.getRowDimension();
+        Map<Integer, Integer> submissionIdx2ClusterIdx = new HashMap<>();
+        int clusterIdx = 0;
+        List<Collection<Integer>> clusters = new ArrayList<>(clustering);
+        for (Collection<Integer> cluster : clusters) {
+            for (Integer submissionIdx : cluster) {
+                submissionIdx2ClusterIdx.put(submissionIdx, clusterIdx);
+            }
+            clusterIdx++;
+        }
+        RealMatrix E = new Array2DRowRealMatrix(clusters.size(), clusters.size());
+        E = E.scalarMultiply(0);
+        for (int i = 0; i < N; i++) {
+            if (!submissionIdx2ClusterIdx.containsKey(i)) continue;
+            int clusterA = submissionIdx2ClusterIdx.get(i);
+            for (int j = i + 1; j < N; j++) {
+                if (!submissionIdx2ClusterIdx.containsKey(j)) continue;
+                int clusterB = submissionIdx2ClusterIdx.get(j);
+                E.addToEntry(clusterA, clusterB, similarity.getEntry(i, j));
+                E.addToEntry(clusterB, clusterA, similarity.getEntry(i, j));
+            }
+        }
+        E = E.scalarMultiply(1 / Arrays.stream(similarity.getData()).flatMapToDouble(DoubleStream::of).sum());
+        for (int i = 0; i < clusters.size(); i++) {
+            double outWeightSum = E.getRowVector(i).getL1Norm();
+            double clusterCommunityStrength = E.getEntry(i, i) - outWeightSum * outWeightSum;
+            this.clusters.add(new DefaultCluster<Integer>(clusters.get(i), (float) clusterCommunityStrength, this));
+            communityStrength += clusterCommunityStrength;
+        }
+        size = this.clusters.stream().mapToInt(x -> x.getMembers().size()).sum();
+    }
+
+    @Override
+    public Collection<Cluster<Integer>> getClusters() {
+        return Collections.unmodifiableCollection(clusters);
+    }
+
+    @Override
+    public float getCommunityStrength() {
+        return (float) communityStrength;
+    }
+
+    @Override
+    public int size() {
+        return size;
+    }
+    
+}

+ 46 - 0
jplag/src/main/java/de/jplag/clustering/IntegerMapping.java

@@ -0,0 +1,46 @@
+package de.jplag.clustering;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * Creates a mapping of any set to integers
+ */
+public class IntegerMapping<T> {
+
+    private HashMap<T, Integer> mapping = new HashMap<>();
+    private List<T> backMapping = new ArrayList<>();
+    private int size = 0;
+    
+    public IntegerMapping(int initialCapacity) {
+        mapping = new HashMap<>(initialCapacity);
+        backMapping = new ArrayList<>(initialCapacity);
+    }
+
+    /**
+     * @param value is added to the mapping (if not already present)
+     * @return the associated integer
+     */
+    public int map(T value) {
+        Integer result = mapping.get(value);
+        if (result == null) {
+            int newIdx = size++;
+            mapping.put(value, newIdx);
+            backMapping.add(value);
+            return newIdx;
+        }
+        return result;
+    }
+
+    public T unmap(int index) {
+        return backMapping.get(index);
+    }
+
+    /**
+     * @return Number of unique values in the mapping
+     */
+    public int size() {
+        return size;
+    }
+}

+ 59 - 0
jplag/src/main/java/de/jplag/clustering/Preprocessor.java

@@ -0,0 +1,59 @@
+package de.jplag.clustering;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.DoubleStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+
+import de.jplag.clustering.algorithm.ClusteringAlgorithm;
+
+public interface Preprocessor {
+    double[][] preprocessSimilarities(double[][] similarityMatrix);
+    Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result);
+
+    public static class PreprocessorHelper {
+        private IntegerMapping<Integer> mapping;
+
+        public double[][] removeDisconnectedEntries(double[][] connections) {
+            List<Integer> rowList = new ArrayList<>();
+            mapping = new IntegerMapping<>(connections.length);
+            RealMatrix similarity = new Array2DRowRealMatrix(connections, true);
+            for (int i = 0; i < similarity.getRowDimension(); i++) {
+                if (DoubleStream.of(similarity.getRow(i)).filter(x -> x > 0).findAny().isPresent()) {
+                    rowList.add(i);
+                    mapping.map(i);
+                }
+            }
+            int[] preservedRows = rowList.stream().mapToInt(Integer::intValue).toArray();
+            similarity = similarity.getSubMatrix(preservedRows, preservedRows);
+            return similarity.getData();
+        }
+
+        public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+            return result.stream().map(cluster -> cluster.stream().map(mapping::unmap).collect(Collectors.toList())).collect(Collectors.toList());
+        }
+    }
+
+    public static class PreprocessedClusteringAlgorithm implements ClusteringAlgorithm {
+
+        private final ClusteringAlgorithm base;
+        private final Preprocessor preprocessor;
+
+        public PreprocessedClusteringAlgorithm(ClusteringAlgorithm base, Preprocessor preprocessor) {
+            this.base = base;
+            this.preprocessor = preprocessor;
+        }
+
+        @Override
+        public Collection<Collection<Integer>> cluster(RealMatrix similarityMatrix) {
+            double[][] data = preprocessor.preprocessSimilarities(similarityMatrix.getData());
+            Collection<Collection<Integer>> prelimResult = base.cluster(new Array2DRowRealMatrix(data, false));
+            return preprocessor.postProcessResult(prelimResult);
+        }
+
+    }
+}

+ 5 - 0
jplag/src/main/java/de/jplag/clustering/Preprocessors.java

@@ -0,0 +1,5 @@
+package de.jplag.clustering;
+
+public enum Preprocessors {
+    NONE, CDF, THRESHOLD, PERCENTILE
+}

+ 878 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/BFGS.java

@@ -0,0 +1,878 @@
+/**
+ * The original version of this file originates from SMILE:
+ * https://github.com/haifengl/smile
+ */
+
+/*******************************************************************************
+ * Copyright (c) 2010-2020 Haifeng Li. All rights reserved.
+ *
+ * Smile is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version.
+ *
+ * Smile is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Smile.  If not, see <https://www.gnu.org/licenses/>.
+ ******************************************************************************/
+
+package de.jplag.clustering.algorithm;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.IntStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.ArrayRealVector;
+import org.apache.commons.math3.linear.DecompositionSolver;
+import org.apache.commons.math3.linear.LUDecomposition;
+import org.apache.commons.math3.linear.MatrixUtils;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.apache.commons.math3.util.Pair;
+
+import static java.lang.Math.abs;
+import static java.lang.Math.max;
+import static java.lang.Math.min;
+import static java.lang.Math.sqrt;
+
+/**
+ * The Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm is an iterative
+ * method for solving unconstrained nonlinear optimization problems.
+ * <p>
+ * The BFGS method belongs to quasi-Newton methods, a class of hill-climbing
+ * optimization techniques that seek a stationary point of a (preferably
+ * twice continuously differentiable) function. For such problems,
+ * a necessary condition for optimality is that the gradient be zero.
+ * Newton's method and the BFGS methods are not guaranteed to converge
+ * unless the function has a quadratic Taylor expansion near an optimum.
+ * However, BFGS has proven to have good performance even for non-smooth
+ * optimizations.
+ * <p>
+ * In quasi-Newton methods, the Hessian matrix of second derivatives is
+ * not computed. Instead, the Hessian matrix is approximated using
+ * updates specified by gradient evaluations (or approximate gradient
+ * evaluations). Quasi-Newton methods are generalizations of the secant
+ * method to find the root of the first derivative for multidimensional
+ * problems. In multi-dimensional problems, the secant equation does not
+ * specify a unique solution, and quasi-Newton methods differ in how they
+ * constrain the solution. The BFGS method is one of the most popular
+ * members of this class.
+ * <p>
+ * Like the original BFGS, the limited-memory BFGS (L-BFGS) uses an
+ * estimation to the inverse Hessian matrix to steer its search
+ * through variable space, but where BFGS stores a dense <code>n × n</code>
+ * approximation to the inverse Hessian (<code>n</code> being the number of
+ * variables in the problem), L-BFGS stores only a few vectors
+ * that represent the approximation implicitly. Due to its resulting
+ * linear memory requirement, the L-BFGS method is particularly well
+ * suited for optimization problems with a large number of variables
+ * (e.g., &gt; 1000). Instead of the inverse Hessian <code>H_k</code>, L-BFGS
+ * maintains * a history of the past <code>m</code> updates of the position
+ * <code>x</code> and gradient <code>∇f(x)</code>, where generally the
+ * history size <code>m</code> can be small (often <code>m &lt; 10</code>).
+ * These updates are used to implicitly do operations requiring the
+ * <code>H_k</code>-vector product.
+ *
+ * <h2>References</h2>
+ * <ol>
+ *     <li>Roger Fletcher. Practical methods of optimization.</li>
+ *     <li>D. Liu and J. Nocedal. On the limited memory BFGS method for large scale optimization. Mathematical Programming B 45 (1989) 503-528.</li>
+ *     <li>Richard H. Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu. A limited memory algorithm for bound constrained optimization.</li>
+ * </ol>
+ *
+ * @author Haifeng Li
+ */
+public class BFGS {
+    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BFGS.class);
+    /** A number close to zero, between machine epsilon and its square root. */
+    private static final double EPSILON = Double.valueOf(System.getProperty("smile.bfgs.epsilon", "1E-10"));
+    /** The convergence criterion on function value. */
+    private static final double TOLF = 4 * EPSILON;
+    /** The scaled maximum step length allowed in line searches. */
+    private static final double STPMX = 100.0;
+
+    /**
+     * Minimize a function along a search direction by find a step which satisfies
+     * a sufficient decrease condition and a curvature condition.
+     * <p>
+     * At each stage this function updates an interval of uncertainty with
+     * endpoints <code>stx</code> and <code>sty</code>. The interval of
+     * uncertainty is initially chosen so that it contains a
+     * minimizer of the modified function
+     * <p>
+     * <pre>
+     *      f(x+stp*s) - f(x) - ftol*stp*(gradf(x)'s).
+     * </pre>
+     * If a step is obtained for which the modified function
+     * has a nonpositive function value and nonnegative derivative,
+     * then the interval of uncertainty is chosen so that it
+     * contains a minimizer of <code>f(x+stp*s)</code>.
+     * <p>
+     * The algorithm is designed to find a step which satisfies
+     * the sufficient decrease condition
+     * <p>
+     * <pre>
+     *       f(x+stp*s) &lt;= f(X) + ftol*stp*(gradf(x)'s),
+     * </pre>
+     * and the curvature condition
+     * <p>
+     * <pre>
+     *       abs(gradf(x+stp*s)'s)) &lt;= gtol*abs(gradf(x)'s).
+     * </pre>
+     * If <code>ftol</code> is less than <code>gtol</code> and if, for example,
+     * the function is bounded below, then there is always a step which
+     * satisfies both conditions. If no step can be found which satisfies both
+     * conditions, then the algorithm usually stops when rounding
+     * errors prevent further progress. In this case <code>stp</code> only
+     * satisfies the sufficient decrease condition.
+     *
+     * @param xold on input this contains the base point for the line search.
+     *
+     * @param fold on input this contains the value of the objective function
+     *             at <code>x</code>.
+     *
+     * @param g on input this contains the gradient of the objective function
+     *          at <code>x</code>.
+     *
+     * @param p the search direction.
+     *
+     * @param x on output, it contains <code>xold + &gamma;*p</code>, where
+     *          &gamma; > 0 is the step length.
+     *
+     * @param stpmax specify upper bound for the step in the line search so that
+     *          we do not try to evaluate the function in regions where it is
+     *          undefined or subject to overflow.
+     *
+     * @return the new function value.
+     */
+    private static double linesearch(MultivariateFunction func, double[] xold, double fold, double[] g, double[] p, double[] x, double stpmax) {
+        if (stpmax <= 0) {
+            throw new IllegalArgumentException("Invalid upper bound of linear search step: " + stpmax);
+        }
+
+        // Termination occurs when the relative width of the interval
+        // of uncertainty is at most xtol.
+        final double xtol = EPSILON;
+        // Tolerance for the sufficient decrease condition.
+        final double ftol = 1.0E-4;
+
+        int n = xold.length;
+
+        // Scale if attempted step is too big
+        double pnorm = norm(p);
+        if (pnorm > stpmax) {
+            double r = stpmax / pnorm;
+            for (int i = 0; i < n; i++) {
+                p[i] *= r;
+            }
+        }
+
+        // Check if s is a descent direction.
+        double slope = 0.0;
+        for (int i = 0; i < n; i++) {
+            slope += g[i] * p[i];
+        }
+
+        if (slope >= 0) {
+            //throw new IllegalArgumentException("Line Search: the search direction is not a descent direction, which may be caused by roundoff problem.");
+        }
+
+        // Calculate minimum step.
+        double test = 0.0;
+        for (int i = 0; i < n; i++) {
+            double temp = abs(p[i]) / max(xold[i], 1.0);
+            if (temp > test) {
+                test = temp;
+            }
+        }
+
+        double alammin = xtol / test;
+        double alam = 1.0;
+
+        double alam2 = 0.0, f2 = 0.0;
+        double a, b, disc, rhs1, rhs2, tmpalam;
+        while (true) {
+            // Evaluate the function and gradient at stp
+            // and compute the directional derivative.
+            for (int i = 0; i < n; i++) {
+                x[i] = xold[i] + alam * p[i];
+            }
+
+            double f = func.f(x);
+
+            // Convergence on &Delta; x.
+            if (alam < alammin) {
+                System.arraycopy(xold, 0, x, 0, n);
+                return f;
+            } else if (f <= fold + ftol * alam * slope) {
+                // Sufficient function decrease.
+                return f;
+            } else {
+                // Backtrack
+                if (alam == 1.0) {
+                    // First time
+                    tmpalam = -slope / (2.0 * (f - fold - slope));
+                } else {
+                    // Subsequent backtracks.
+                    rhs1 = f - fold - alam * slope;
+                    rhs2 = f2 - fold - alam2 * slope;
+                    a = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2)) / (alam - alam2);
+                    b = (-alam2 * rhs1 / (alam * alam) + alam * rhs2 / (alam2 * alam2)) / (alam - alam2);
+                    if (a == 0.0) {
+                        tmpalam = -slope / (2.0 * b);
+                    } else {
+                        disc = b * b - 3.0 * a * slope;
+                        if (disc < 0.0) {
+                            tmpalam = 0.5 * alam;
+                        } else if (b <= 0.0) {
+                            tmpalam = (-b + sqrt(disc)) / (3.0 * a);
+                        } else {
+                            tmpalam = -slope / (b + sqrt(disc));
+                        }
+                    }
+                    if (tmpalam > 0.5 * alam) {
+                        tmpalam = 0.5 * alam;
+                    }
+                }
+            }
+            alam2 = alam;
+            f2 = f;
+            alam = max(tmpalam, 0.1 * alam);
+        }
+    }
+
+    /**
+     * This method solves the bound constrained minimization problem
+     * using the L-BFGS-B method. The L-BFGS-B algorithm extends L-BFGS
+     * to handle simple box constraints on variables; that is, constraints
+     * of the form li ≤ xi ≤ ui where li and ui are per-variable constant
+     * lower and upper bounds, respectively (for each xi, either or both
+     * bounds may be omitted). The method works by identifying fixed and
+     * free variables at every step (using a simple gradient method),
+     * and then using the L-BFGS method on the free variables only to
+     * get higher accuracy, and then repeating the process.
+     *
+     * @param func the function to be minimized.
+     *
+     * @param m the number of corrections used in the L-BFGS update.
+     *          Values of <code>m</code> less than 3 are not recommended;
+     *          large values of <code>m</code> will result in excessive
+     *          computing time. <code>3 &lt;= m &lt;= 7</code> is recommended.
+     *          A common choice for m is m = 5.
+     *
+     * @param x on initial entry this must be set by the user to the values
+     *          of the initial estimate of the solution vector. On exit with
+     *          <code>iflag = 0</code>, it contains the values of the variables
+     *          at the best point found (usually a solution).
+     *
+     * @param l the lower bound.
+     * @param u the upper bound.
+     * @param gtol the convergence tolerance on zeroing the gradient.
+     * @param maxIter the maximum number of iterations.
+     *
+     * @return the minimum value of the function.
+     */
+    public static double minimize(DifferentiableMultivariateFunction func, int m, double[] x, double[] l, double[] u, double gtol, int maxIter) {
+        if (gtol <= 0.0) {
+            throw new IllegalArgumentException("Invalid gradient tolerance: " + gtol);
+        }
+
+        if (maxIter <= 0) {
+            throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter);
+        }
+
+        if (m <= 0) {
+            throw new IllegalArgumentException("Invalid m: " + m);
+        }
+
+        if (l.length != x.length) {
+            throw new IllegalArgumentException("Invalid lower bound size: " + l.length);
+        }
+
+        if (u.length != x.length) {
+            throw new IllegalArgumentException("Invalid upper bound size: " + u.length);
+        }
+
+        int n = x.length;
+        double theta = 1.0;
+
+        Matrix Y = null, S = null;
+        Matrix W = new Matrix(n, 1);
+        Matrix M = new Matrix(1, 1);
+
+        ArrayList<double[]> yHistory = new ArrayList<>();
+        ArrayList<double[]> sHistory = new ArrayList<>();
+        double[] y = new double[n];
+        double[] s = new double[n];
+
+        double[] p = new double[n];
+        double[] g = new double[n];
+        double[] cauchy = new double[n];
+        double f   = func.g(x, g);
+
+        double[] x_old = new double[n];
+        double[] g_old = new double[n];
+
+        // Upper limit for line search step.
+        double stpmax = STPMX * max(norm(x), n);
+
+        for (int iter = 1; iter <= maxIter; iter++) {
+            double f_old   = f;
+            System.arraycopy(x, 0, x_old, 0, n);
+            System.arraycopy(g, 0, g_old, 0, n);
+
+            // STEP 2: compute the cauchy point
+            System.arraycopy(x, 0, cauchy, 0, n);
+            double[] c = cauchy(x, g, cauchy, l, u, theta, W, M);
+            clampToBound(cauchy, l, u);
+
+            // STEP 3: compute a search direction d_k by the primal method for the sub-problem
+            double[] subspaceMin = subspaceMinimization(x, g, cauchy, c, l, u, theta, W, M);
+            clampToBound(subspaceMin, l, u);
+
+            // STEP 4: perform line search
+            for (int i = 0; i < n; i++) {
+                p[i] = subspaceMin[i] - x[i];
+            }
+            linesearch(func, x_old, f_old, g, p, x, stpmax);
+            clampToBound(x, l, u);
+
+            for (double xi : x) {
+                if (Double.isNaN(xi) || Double.isInfinite(xi)) {
+                    logger.warn("L-BFGS-B: bad x produced by line search, return previous good x");
+                    System.arraycopy(x_old, 0, x, 0, n);
+                    return f_old;
+                }
+            }
+
+            // STEP 5: compute gradient update current guess and function information
+            f = func.g(x, g);
+            if (Double.isNaN(f) || Double.isInfinite(f)) {
+                logger.warn("L-BFGS-B: bad f(x) produced by line search, return previous good x");
+                System.arraycopy(x_old, 0, x, 0, n);
+                return f_old;
+            }
+
+            if (gnorm(x, g, l, u) < gtol) {
+                logger.info(String.format("L-BFGS-B converges on gradient after %d iterations: %.5f", iter, f));
+                return f;
+            }
+
+            if (iter % 100 == 0) {
+                logger.info(String.format("L-BFGS-B: the function value after %3d iterations: %.5f", iter, f));
+            }
+
+            // prepare for next iteration
+            for (int i = 0; i < n; i++) {
+                y[i] = g[i] - g_old[i];
+                s[i] = x[i] - x_old[i];
+            }
+
+            // STEP 6
+            double sy = dot(s, y);
+            double yy = dot(y, y);
+            double test = abs(sy);
+            if (test > EPSILON * yy) {
+                if (yHistory.size() >= m) {
+                    yHistory.remove (0);
+                    sHistory.remove (0);
+                }
+
+                yHistory.add(y);
+                sHistory.add(s);
+
+                int h = yHistory.size();
+                if (iter <= m) {
+                    Y = new Matrix(n, h);
+                    S = new Matrix(n, h);
+                    W = new Matrix(n, 2*h);
+                    M = new Matrix(2*h, 2*h);
+                }
+
+                // STEP 7
+                theta = yy / sy;
+                for (int j = 0; j < h; j++) {
+                    double[] yj = yHistory.get(j);
+                    double[] sj = sHistory.get(j);
+
+                    for (int i = 0; i < n; i++) {
+                        Y.set(i, j, yj[i]);
+                        S.set(i, j, sj[i]);
+                        W.set(i, j, yj[i]);
+                        W.set(i, h+j, sj[i] * theta);
+                    }
+                }
+
+                Matrix SY = S.tm(Y);
+                Matrix SS = S.ata();
+                for (int j = 0; j < h; j++) {
+                    M.set(j, j, -SY.get(j, j));
+                    for (int i = 0; i <= j; i++) {
+                        M.set(h+i, j, 0.0);
+                        M.set(j, h+i, 0.0);
+                    }
+
+                    for (int i = j+1; i < h; i++) {
+                        M.set(h+i, j, SY.get(i, j));
+                        M.set(j, h+i, SY.get(i, j));
+                    }
+
+                    for (int i = 0; i < h; i++) {
+                        M.set(h+i, h+j, theta * SS.get(i, j));
+                    }
+                }
+
+                //M.uplo(UPLO.LOWER);
+                M = M.inverse();
+            }
+
+            logger.debug("L-BFGS-B iteration {} moves from {} to {} where f(x) = {}", iter, Arrays.toString(x_old), Arrays.toString(x), f);
+
+            if (abs(f_old - f) < TOLF) {
+                logger.info(String.format("L-BFGS-B converges on f(x) after %d iterations: %.5f", iter, f));
+                return f;
+            }
+        }
+
+        logger.warn(String.format("L-BFGS-B reaches maximum %d iterations: %.5f", maxIter, f));
+        return f;
+    }
+
+    private static double dot(double[] a, double[] b) {
+        if (a.length != b.length) {
+            throw new IllegalArgumentException("a and b have different lengths");
+        }
+        double sum = 0;
+        for (int i = 0; i < a.length; i++) {
+            sum += a[i] * b[i];
+        }
+        return sum;
+    }
+
+    private static double norm(double[] a) {
+        return Math.sqrt(dot(a, a));
+    }
+
+    /**
+     * Algorithm CP: Computation of the Generalized Cauchy Point. See page 8.
+     * @param x  the parameter vector
+     * @param g  the gradient vector
+     */
+    private static double[] cauchy(double[] x, double[] g, double[] cauchy, double[] l, double[] u, double theta, Matrix W, Matrix M) {
+        int n = x.length;
+        double[] t = new double[n];
+        double[] d = new double[n];
+
+        for (int i = 0; i < n; i++) {
+            t[i] = g[i] == 0 ? Double.MAX_VALUE
+                : (g[i] <  0 ? (x[i] - u[i]) / g[i]
+                             : (x[i] - l[i]) / g[i]);
+            if (t[i] != 0.0) d[i] = -g[i];
+        }
+
+        int[] index = sortWithIndex(t);
+        double[] p = W.tv(d);
+        double[] c = new double[p.length];
+        double fPrime = -dot(d, d);
+        double fDoublePrime  = max(-theta * fPrime - M.xAx(p), EPSILON);
+        double f_dp_orig     = fDoublePrime;
+        double dt_min        = -fPrime / fDoublePrime;
+        double t_old         = 0.0;
+
+        int i = 0;
+        for (; i < n; i++) {
+            if (t[index[i]] >= 0) break;
+        }
+
+        double dt = t[i];
+        for (; dt_min >= dt && i < n; i++) {
+            int b = index[i];
+            double tb = t[i];
+            dt = tb - t_old;
+
+            cauchy[b] = d[b] > 0 ? u[b] :
+                       (d[b] < 0 ? l[b] : cauchy[b]);
+            double zb = cauchy[b] - x[b];
+            for (int j = 0; j < c.length; j++) {
+                c[j] += p[j] * dt;
+            }
+
+            double gb = g[b];
+            double[] wbt  = W.row(b);
+            fPrime       += dt * fDoublePrime + gb * gb + theta * gb * zb - gb * dot(wbt, M.mv(c));
+            fDoublePrime -= theta * gb * gb + 2.0 * gb * dot(wbt, M.mv(p)) + gb * gb * M.xAx(wbt);
+            fDoublePrime  = max(fDoublePrime, EPSILON * f_dp_orig);
+            for (int j = 0; j < p.length; j++) {
+                p[j] += wbt[j] * gb;
+            }
+
+            d[b]          = 0;
+            dt_min        = -fPrime / fDoublePrime;
+            t_old         = tb;
+        }
+
+        dt_min = max(dt_min, 0.0);
+        t_old += dt_min;
+
+        for (int ii = i; ii < n; ii++) {
+            int si = index[ii];
+            cauchy[si] = x[si] + t_old * d[si];
+        }
+
+        for (int j = 0; j < c.length; j++) {
+            c[j] += p[j] * dt_min;
+        }
+
+        return c;
+    }
+
+    /**
+     * Minimization of the subspace of free variables. See Section 5 on page 9.
+     * @param x        the parameter vector
+     * @param g        the gradient vector
+     * @param cauchy   the cauchy points
+     * @param c        vector obtained from gcp() used to initialize the subspace
+     *                 minimization process
+     */
+    private static double[] subspaceMinimization(double[] x, double[] g, double[] cauchy, double[] c, double[] l, double[] u, double theta, Matrix W, Matrix M) {
+        int n = x.length;
+        double thetaInverse = 1.0 / theta;
+        ArrayList<Integer> freeVarIdx = new ArrayList<>();
+        for (int i = 0; i < n; i++) {
+            if (cauchy[i] != u[i] && cauchy[i] != l[i]) {
+                freeVarIdx.add(i);
+            }
+        }
+
+        if (freeVarIdx.isEmpty()) {
+            return cauchy.clone();
+        }
+
+        int freeVarCount = freeVarIdx.size();
+        int[] freeVar = new int[freeVarCount];
+        for (int i = 0; i < freeVarCount; i++) {
+            freeVar[i] = freeVarIdx.get(i);
+        }
+
+        double[] wmc = W.mv(M.mv(c));
+        double[] r = new double[freeVarCount];
+        for (int i = 0; i < freeVarCount; i++) {
+            int fi = freeVar[i];
+            r[i] = g[fi] + (cauchy[fi] - x[fi]) * theta - wmc[fi];
+        }
+
+        Matrix WZ = W.row(freeVar);
+        double[] v  = M.mv(WZ.tv(r));
+        Matrix N = WZ.ata().mul(-thetaInverse);
+        N = M.mm(N);
+        int n1 = N.nrows();
+        for (int i = 0; i < n1; i++) {
+            N.add(i, i, 1.0);
+        }
+
+        DecompositionSolver lu = N.lu();
+        v = lu.solve(new ArrayRealVector(v)).toArray();
+
+        double[] wzv = WZ.mv(v);
+
+        double[] du = new double[freeVarCount];
+        for (int i = 0; i < freeVarCount; i++) {
+            du[i] = -thetaInverse * (r[i] + wzv[i] * thetaInverse);
+        }
+        double alphaStar = findAlpha(cauchy, du, l, u, freeVar);
+        double[] dStar   = new double[freeVarCount];
+        for (int i = 0; i < freeVarCount; i++) {
+            dStar[i] = du[i] * alphaStar;
+        }
+
+        double[] subspaceMin = cauchy.clone();
+        for (int i = 0; i < freeVarCount; i++) {
+            subspaceMin[freeVar[i]] += dStar[i];
+        }
+
+        return subspaceMin;
+    }
+
+    /**
+     * Find the alpha* parameter, a positive scalar. See Equation 5.8 on page 11.
+     * @param cauchy   cauchy point
+     * @param du       intermediate results used to find alpha*
+       @param freeVar  the indices of free variable
+     */
+    private static double findAlpha(double[] cauchy, double[] du, double[] l, double[] u, int[] freeVar) {
+        double alphaStar = 1.0;
+        int n = freeVar.length;
+
+        for (int i = 0; i < n; i++) {
+            int fi = freeVar[i];
+            alphaStar = du[i] > 0 ? min(alphaStar, (u[fi] - cauchy[fi]) / du[i])
+                                  : min(alphaStar, (l[fi] - cauchy[fi]) / du[i]);
+        }
+
+        return alphaStar;
+    }
+
+    /**
+     * Returns the infinity norm of  gradient.
+     * @param x  the parameter vector
+     * @param g  the gradient vector
+     */
+    private static double gnorm(double[] x, double[] g, double[] l, double[] u) {
+        double norm = 0.0;
+        int n = x.length;
+
+        for (int i = 0; i < n; i++) {
+            double gi = g[i];
+            if (gi < 0) gi = max(x[i] - u[i], gi);
+            else gi = min(x[i] - l[i], gi);
+            norm = max(norm, abs(gi));
+        }
+
+        return norm;
+    }
+
+    /**
+     * Clamps the values of v to stay within the pre-defined bounds.
+     * @param v  the vector to be adjusted
+     */
+    private static void clampToBound(double[] v, double[] l, double[] u) {
+        int n = v.length;
+
+        for (int i = 0; i < n; i++) {
+            if (v[i] > u[i]) v[i] = u[i];
+            else if (v[i] < l[i]) v[i] = l[i];
+        }
+    }
+
+    public interface MultivariateFunction {
+        /**
+         * Computes the value of the function at x.
+         * @param x a real vector.
+         * @return the function value.
+         */
+        double f(double[] x);
+    }
+
+    public interface DifferentiableMultivariateFunction extends MultivariateFunction {
+        /** A number close to zero, between machine epsilon and its square root. */
+        double EPSILON = Double.parseDouble(System.getProperty("smile.gradient.epsilon", "1E-8"));
+    
+        /**
+         * Computes the value and gradient at x. The default implementation
+         * uses finite differences to calculate the gradient. When possible,
+         * the subclass should compute the gradient analytically.
+         *
+         * @param x a real vector.
+         * @param gradient the output variable of gradient.
+         * @return the function value.
+         */
+        default double g(double[] x, double[] gradient) {
+            double fx = f(x);
+    
+            int n = x.length;
+            double[] xh = new double[n];
+            for (int i = 0; i < n; i++) {
+                System.arraycopy(x, 0, xh, 0, n);
+                double xi = x[i];
+                double h = EPSILON * Math.abs(xi);
+                if (h == 0.0) {
+                    h = EPSILON;
+                }
+                xh[i] = xi + h; // trick to reduce finite-precision error.
+                h = xh[i] - xi;
+    
+                double fh = f(xh);
+                xh[i] = xi;
+                gradient[i] = (fh - fx) / h;
+            }
+    
+            return fx;
+        }
+    }
+
+    private static int[] sortWithIndex(double[] array) {
+        List<Pair<Integer, Double>> sortedPairs = IntStream.range(0, array.length)
+            .mapToObj(idx -> Pair.create(idx, array[idx]))
+            .sorted(Comparator.comparingDouble(Pair::getValue))
+            .toList();
+        double[] sortedDoubles = sortedPairs.stream().mapToDouble(Pair::getValue).toArray();
+        int[] sortedIndices = sortedPairs.stream().mapToInt(Pair::getKey).toArray();
+        System.arraycopy(sortedDoubles, 0, array, 0, array.length);
+        return sortedIndices;
+    }
+
+    /**
+     * This is a substitute for SMILE's matrix implementation.
+     */
+    private static class Matrix {
+
+        private RealMatrix d;
+        private int m;
+        private int n;
+
+        /**
+         * Constructor of zero matrix.
+         * @param m the number of rows.
+         * @param n the number of columns.
+         */
+        public Matrix(RealMatrix delegate) {
+            d = delegate;
+            this.m = delegate.getRowDimension();
+            this.n = delegate.getColumnDimension();
+        }
+
+        /**
+         * Constructor of zero matrix.
+         * @param m the number of rows.
+         * @param n the number of columns.
+         */
+        public Matrix(int m, int n) {
+            d = new Array2DRowRealMatrix(m, n);
+            this.m = m;
+            this.n = n;
+        }
+
+        /**
+         * Sets {@code A[i,j] = x}.
+         * @param i the row index.
+         * @param j the column index.
+         * @param x the matrix cell value.
+         */
+        public void set(int i, int j, double x) {
+            d.setEntry(i, j, x);
+        }
+
+        /**
+         * Returns matrix multiplication {@code A' * B}.
+         * @param B the operand.
+         * @return the multiplication.
+         */
+        public Matrix tm(Matrix B) {
+            if (d.getRowDimension() != B.d.getRowDimension()) {
+                throw new IllegalArgumentException(String.format("Matrix multiplication A' * B: %d x %d vs %d x %d", m, n, B.m, B.n));
+            }
+
+            return new Matrix(d.transpose().multiply(B.d));
+        }
+
+        /**
+         * Returns {@code A' * A}.
+         * @return {@code A' * A}.
+         */
+        public Matrix ata() {
+            Matrix C = new Matrix(d.transpose().multiply(d));
+            // C.mm(TRANSPOSE, 1this, NO_TRANSPOSE, this);
+            //C.uplo(LOWER);
+            return C;
+        }
+        
+        /**
+         * Returns {@code A[i,j]}.
+         * @param i the row index.
+         * @param j the column index.
+         * @return the matrix cell value.
+         */
+        public double get(int i, int j) {
+            return d.getEntry(i, j);
+        }
+
+        /**
+         * Returns the inverse of matrix. For pseudo inverse, use QRDecomposition.
+         * @return the inverse of matrix.
+         */
+        public Matrix inverse() {
+            return new Matrix(MatrixUtils.inverse(d));
+        }
+
+        /**
+         * Returns Matrix-vector multiplication {@code A' * x}.
+         * @param x the vector.
+         * @return the matrix-vector multiplication {@code A' * x}.
+         */
+        public double[] tv(double[] x) {
+            return d.transpose().operate(x);
+        }
+
+        /**
+         * Returns the quadratic form {@code x' * A * x}.
+         * The left upper sub-matrix of A is used in the computation based
+         * on the size of x.
+         * @param x the vector.
+         * @return the quadratic form.
+         */
+        public double xAx(double[] x) {
+            if (m != n) {
+                throw new IllegalArgumentException(String.format("The matrix is not square: %d x %d", m, n));
+            }
+
+            if (n != x.length) {
+                throw new IllegalArgumentException(String.format("Matrix: %d x %d, Vector: %d", m, n, x.length));
+            }
+
+            double[] Ax = mv(x);
+            return new ArrayRealVector(x).dotProduct(new ArrayRealVector(Ax));
+        }
+
+        /**
+         * Returns the matrix-vector multiplication {@code A * x}.
+         * @param x the vector.
+         * @return the matrix-vector multiplication {@code A * x}.
+         */
+        public double[] mv(double[] x) {
+            return d.operate(x);
+        }
+
+        /**
+         * Returns the i-th row. Negative index -i means the i-th row from the end.
+         * @param i the row index.
+         * @return the row.
+         */
+        public double[] row(int i) {
+            i = i < 0 ? m + i : i;
+            return d.getRow(i);
+        }
+
+        /**
+        * Returns the matrix of selected rows. Negative index -i means the i-th row from the end.
+        * @param rows the row indices.
+        * @return the sub-matrix.
+        */
+        public Matrix row(int... rows) {
+            double[][] data = new double[rows.length][n];
+
+            for (int i = 0; i < rows.length; i++) {
+                double[] row = row(rows[i]);
+                System.arraycopy(row, 0, data[i], 0, n);
+            }
+
+            return new Matrix(new Array2DRowRealMatrix(data, false));
+        }
+
+        public Matrix mul(double e) {
+            return new Matrix(d.scalarMultiply(e));
+        }
+
+        public Matrix mm(Matrix n2) {
+            return new Matrix(d.multiply(n2.d));
+        }
+
+        public int nrows() {
+            return m;
+        }
+
+        public void add(int m, int n, double e) {
+            d.addToEntry(m, n, e);
+        }
+
+        public DecompositionSolver lu() {
+            return new LUDecomposition(d).getSolver();
+        }
+        
+    }
+}

+ 188 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/BayesianOptimization.java

@@ -0,0 +1,188 @@
+package de.jplag.clustering.algorithm;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Spliterator;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.apache.commons.math3.distribution.NormalDistribution;
+import org.apache.commons.math3.exception.DimensionMismatchException;
+import org.apache.commons.math3.exception.OutOfRangeException;
+import org.apache.commons.math3.linear.ArrayRealVector;
+import org.apache.commons.math3.linear.RealVector;
+import org.apache.commons.math3.random.HaltonSequenceGenerator;
+import org.apache.commons.math3.random.RandomVectorGenerator;
+
+public class BayesianOptimization {
+
+    private static final int STOP_AFTER_CONSECUTIVE_RANDOM_PICKS = 3;
+    private static final int MAX_NON_ZERO_ACQ_FN_EVALS_PER_ITERATION = 50;
+    private static final int MAXIMUM_ACQ_FN_EVALS_PER_ITERATION = 1000;
+
+    private RealVector minima;
+    private RealVector maxima;
+    private int maxEvaluations;
+    private int initialPoints;
+    private double noise;
+    private RealVector lengthScale;
+    public boolean debug = false;
+    
+    /**
+     * 
+     * @param minima of the explored parameters
+     * @param maxima of the explored parameters
+     * @param initPoints points that are initially sampled for exploration
+     * @param maxEvaluations maximal evaluations of the fitted function
+     * @param noise of the explored function
+     * @param lengthScale width parameter for the matern kernel
+     */
+    public BayesianOptimization(RealVector minima, RealVector maxima, int initPoints, int maxEvaluations, double noise, RealVector lengthScale) {
+        if (minima.getDimension() != maxima.getDimension()) {
+            throw new DimensionMismatchException(minima.getDimension(), maxima.getDimension());
+        }
+        if (initPoints < 1 || initPoints > maxEvaluations) {
+            throw new OutOfRangeException(initPoints, 1, maxEvaluations);
+        }
+        this.maxima = maxima;
+        this.minima = minima;
+        this.initialPoints = initPoints;
+        this.maxEvaluations = maxEvaluations;
+        this.noise = noise;
+        this.lengthScale = lengthScale;
+    }
+
+    private Stream<RealVector> sampleSolutionSpace() {
+        RandomVectorGenerator g = new HaltonSequenceGenerator(minima.getDimension());
+        RealVector size = maxima.subtract(minima);
+        return Stream.generate(g::nextVector)
+            .map(x -> new ArrayRealVector(x))
+            .map(x -> x.ebeMultiply(size))
+            .map(x -> x.add(minima));
+
+    }
+
+    private GaussianProcess fit(List<RealVector> X, List<Double> Y) {
+        return GaussianProcess.fit(X, Y.stream().mapToDouble(Double::doubleValue).toArray(), noise, true, lengthScale.toArray());
+    }
+
+    private double acquisitionFunction(GaussianProcess gpr, double[] r, double yMax) {
+        // expected improvement
+        double[] meanStd = gpr.predictWidthStd(new ArrayRealVector(r));
+        double mean = meanStd[0];
+        double std = meanStd[1];
+        double a = mean - yMax;
+        double z = a / std;
+        NormalDistribution norm = new NormalDistribution(null, 0, 1);
+        return a * norm.cumulativeProbability(z) + std * norm.density(z);
+    }
+
+    private static <T> Optional<T> getNext(Spliterator<T> spliterator) {
+        final List<T> result = new ArrayList<>(1);
+
+        if (spliterator.tryAdvance(result::add)) {
+            return Optional.of(result.get(0));
+        } else {
+            return Optional.empty();
+        }
+    }
+
+    /**
+     * Numerically optimize acquisition function
+     */
+    private RealVector maxAcq(GaussianProcess gpr, double yMax, Spliterator<RealVector> samples, double[] randomPicks) {
+        double bestScore = Double.NEGATIVE_INFINITY;
+        double[] bestSolution = getNext(samples).orElseThrow().toArray();
+        double[] min = minima.toArray();
+        double[] max = maxima.toArray();
+        
+        int nonZeroAcquisitions = 0;
+        for (int i = 0; i < MAXIMUM_ACQ_FN_EVALS_PER_ITERATION && nonZeroAcquisitions < MAX_NON_ZERO_ACQ_FN_EVALS_PER_ITERATION; i++) {
+            double[] r = getNext(samples).orElseThrow().toArray();
+            if (acquisitionFunction(gpr, r, yMax) == 0) continue;
+            nonZeroAcquisitions++;
+            double poi = -BFGS.minimize(x -> -acquisitionFunction(gpr, x, yMax), 5, r, min, max, 0.00001, 1000);
+            // Sometimes result is out of bounds (might be due to numerical errors?)
+            for (int j = 0; j< r.length; j++) {
+                r[j] = Math.min(max[j], r[j]);
+                r[j] = Math.max(min[j], r[j]);
+            } 
+            if(poi > bestScore) {
+                bestSolution = r;
+                bestScore = poi;
+            }
+        }
+        if (nonZeroAcquisitions == 0) {
+            randomPicks[0]++;
+        } else {
+            randomPicks[0] = 0;
+        }
+        return new ArrayRealVector(bestSolution);
+    }
+
+    public <T> OptimizationResult<T> maximize(Function<RealVector, OptimizationResult<T>> f) {
+        List<Double> Y = new ArrayList<>(maxEvaluations);
+        List<RealVector> X = new ArrayList<>(maxEvaluations);
+        OptimizationResult<T> best = null;
+
+        // the first couple of executions are reserved for exploration
+        sampleSolutionSpace()
+            .limit(initialPoints)
+            .forEach(X::add);
+
+        Spliterator<RealVector> poiSampler = sampleSolutionSpace().spliterator();
+        double[] zeroAcquisitionsCounter = new double[1];
+
+        while (Y.size() < maxEvaluations && zeroAcquisitionsCounter[0] < STOP_AFTER_CONSECUTIVE_RANDOM_PICKS) {
+            int idx = Y.size();
+            RealVector x;
+            if (idx < X.size()) {
+                // hard coded exploration
+                x = X.get(idx);
+            } else {
+                // GPR
+                GaussianProcess gpr = fit(X, Y);
+                if (debug) {
+                    System.out.println(gpr.toString(minima, maxima, 100, 25, 0));
+                }
+                x = maxAcq(gpr, best.score, poiSampler, zeroAcquisitionsCounter);
+                X.add(x);
+            }
+            OptimizationResult<T> result = f.apply(x);
+            result.params = x;
+            Y.add(result.getScore());
+            if (best == null) {
+                best = result;
+            } else if (result.score > best.score) {
+                best = result;
+            }
+        }
+
+        return best;
+    }
+
+    public static final class OptimizationResult<T> {
+
+        private double score;
+        private T value;
+        private RealVector params;
+
+        public OptimizationResult(double score, T value) {
+            this.score = score;
+            this.value = value;
+        }
+
+        public T getValue() {
+            return value;
+        }
+
+        public double getScore() {
+            return score;
+        }
+
+        public RealVector getParams() {
+            return params;
+        }
+    } 
+}

+ 9 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/ClusteringAlgorithm.java

@@ -0,0 +1,9 @@
+package de.jplag.clustering.algorithm;
+
+import java.util.Collection;
+
+import org.apache.commons.math3.linear.RealMatrix;
+
+public interface ClusteringAlgorithm {
+    Collection<Collection<Integer>> cluster(RealMatrix similarityMatrix);
+}

+ 204 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/GaussianProcess.java

@@ -0,0 +1,204 @@
+package de.jplag.clustering.algorithm;
+
+import java.text.MessageFormat;
+import java.util.List;
+import java.util.OptionalInt;
+import java.util.function.DoubleToIntFunction;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.ArrayRealVector;
+import org.apache.commons.math3.linear.CholeskyDecomposition;
+import org.apache.commons.math3.linear.DiagonalMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.apache.commons.math3.linear.RealVector;
+import org.apache.commons.math3.stat.StatUtils;
+
+public class GaussianProcess {
+
+    private List<RealVector> X;
+    private RealVector weight;
+    private double mean;
+    private double standardDeviation;
+    private CholeskyDecomposition cholesky;
+    private RealVector lengthScale;
+
+    private GaussianProcess(List<RealVector> X, RealVector weight, double mean, double standardDeviation, CholeskyDecomposition cholesky, RealVector lengthScale) {
+        this.X = X;
+        this.weight = weight;
+        this.mean = mean;
+        this.standardDeviation = standardDeviation;
+        this.cholesky = cholesky;
+        this.lengthScale = lengthScale;
+    }
+
+     /**
+     * @param x position to predict at
+     * @return mean prediction at x
+     */
+    public double predict(RealVector x) {
+        RealVector k = maternKernel(X, x, lengthScale);
+
+        double mu = weight.dotProduct(k);
+
+        return mu * this.standardDeviation + this.mean;
+    }
+
+    /**
+     * @param x position to predict at
+     * @return array containing the predicted [mean, std] at x.
+     */
+    public double[] predictWidthStd(RealVector x) {
+        RealVector k = maternKernel(X, x, lengthScale);
+        RealVector Kx = cholesky.getSolver().solve(k);
+
+        double mu = weight.dotProduct(k);
+        double sd = Math.sqrt(maternKernel(x, x, lengthScale) - Kx.dotProduct(k));
+
+        double[] out = new double[2];
+        out[0] = mu * this.standardDeviation + this.mean;
+        out[1] = sd * this.standardDeviation;
+
+        if (Double.isNaN(out[1])) {
+            out[1] = 0;
+        }
+
+        return out;
+    }
+
+    private static final double SQRT_5 = Math.sqrt(5);
+
+    /**
+     * Identical to {@link GaussianProcess#fit(List, double[], double, boolean, double[])} but using a one vector as length scale.
+     * 
+     * @param X 
+     * @param Y expected to have zero mean, unit variance if normalize is false
+     * @param noise variance of noise in Y
+     * @param normalize for Y
+     */
+    public static GaussianProcess fit(List<RealVector> X, double[] Y, double noise, boolean normalize) {
+        return fit(X, Y, noise, normalize, new ArrayRealVector(X.get(0).getDimension(), 1).toArray());
+    }
+    
+    /**
+     * Fit Gaussian Process using a matern kernel.
+     * 
+     * @param X  
+     * @param Y expected to have zero mean, unit variance if normalize is false
+     * @param noise variance of noise in Y
+     * @param normalize if Y should be normalized
+     * @param lengthScale X values are divided by these values before calculating their euclidean distance. If all entries are equal the kernel is isometric.
+     */
+    public static GaussianProcess fit(List<RealVector> X, double[] Y, double noise, boolean normalize, double[] lengthScale) {
+        if (X.size() != Y.length) {
+            throw new IllegalArgumentException(MessageFormat.format("X and Y are of different dimensions {0} and {1}", X.size(), Y.length));
+        }
+        OptionalInt brokenXIndex = IntStream.range(1, X.size()).filter(i -> X.get(i).getDimension() != X.get(i-1).getDimension()).findFirst();
+        brokenXIndex.ifPresent(brokenIndex -> {
+            throw new IllegalArgumentException(MessageFormat.format("X has different dimensions at index {0} ({2}) and index {1} ({3})", brokenIndex - 1, brokenXIndex, X.get(brokenIndex - 1).getDimension(), X.get(brokenIndex).getDimension()));
+        });
+        if (noise <= 0) {
+            throw new IllegalArgumentException(MessageFormat.format("noise must be strictly positive, got {0}", noise));
+        }
+        if (lengthScale.length != X.get(0).getDimension()) {
+            throw new IllegalArgumentException(MessageFormat.format("lengthScale is of different dimension {0} than X values {1}", lengthScale.length, X.get(0).getDimension()));
+        }
+        double mean = 0;
+        double standardDeviation = 1;
+        if (normalize) {
+            mean = StatUtils.mean(Y);
+            standardDeviation = Math.sqrt(StatUtils.variance(Y, mean));
+            for (int i = 0; i < Y.length; i++) {
+                Y[i] = (Y[i] - mean) / standardDeviation;
+            }
+        }
+        RealVector yVector = new ArrayRealVector(Y);
+        RealVector scaleV = new ArrayRealVector(lengthScale);
+
+        RealMatrix k = maternKernel(X, scaleV);
+        k = k.add(new DiagonalMatrix(DoubleStream.generate(() -> noise).limit(X.size()).toArray(), false));
+
+        CholeskyDecomposition choDec = new CholeskyDecomposition(k);
+        RealVector w = choDec.getSolver().solve(yVector);
+    
+        return new GaussianProcess(X, w, mean, standardDeviation, choDec, scaleV);
+    }
+
+    /**
+     * Matern kernel for nu=2.5 (we get a twice differentiable gp) 
+     */
+    private static RealMatrix maternKernel(List<RealVector> X, RealVector lengthScale) {
+        RealMatrix k = new Array2DRowRealMatrix(X.size(), X.size());
+        for (int i = 0; i < X.size(); i++) {
+            RealVector left = X.get(i);
+            for (int j = i; j < X.size(); j++) {
+                RealVector right = X.get(j);
+                double maternVal = maternKernel(left, right, lengthScale);
+                k.setEntry(i, j, maternVal);
+                k.setEntry(j, i, maternVal);
+            }
+        }
+        return k;
+    }
+
+    private static RealVector maternKernel(List<RealVector> X, RealVector v, RealVector lengthScale) {
+        RealVector out = new ArrayRealVector(X.size());
+        for (int i = 0; i < X.size(); i++) {
+            out.setEntry(i, maternKernel(X.get(i), v, lengthScale));
+        }
+        return out;
+    }
+
+    private static double maternKernel(RealVector left, RealVector right, RealVector lengthScale) {
+        double dist = left.ebeDivide(lengthScale).getDistance(right.ebeDivide(lengthScale));
+        dist *= SQRT_5;
+        return (1 + dist) * Math.exp(-dist);
+    }
+
+    /**
+     * ascii graph for debugging
+     */
+    public String toString(RealVector min, RealVector max, int width, int height, double minY) {
+        char[][] out = new char[height][width];
+        for (int i = 0; i < height; i++) {
+            for (int j = 0; j < width; j++) {
+                out[i][j] = ' ';
+            }
+        }
+        double[] mean = new double[width];
+        double[] std = new double[width];
+        for (int i = 0; i < width; i++) {
+            double t = (i + 0.5) / width;
+            RealVector x = min.add(max.subtract(min).mapMultiplyToSelf(t));
+            double[] meanStd = predictWidthStd(x);
+            mean[i] = meanStd[0];
+            std[i] = meanStd[1];
+        }
+        double[] upperBorder = IntStream.range(0, width).mapToDouble(i -> mean[i] + std[i]).toArray();
+        double[] lowerBorder = IntStream.range(0, width).mapToDouble(i -> mean[i] - std[i]).toArray();
+        double minVal = Math.max(DoubleStream.of(lowerBorder).min().orElseThrow(), minY);
+        double maxVal = DoubleStream.of(upperBorder).max().orElseThrow();
+        double range = maxVal - minVal;
+        DoubleToIntFunction toCharPos = x -> (int) Math.round(height - height * (x - minVal) / range);
+        int[] upperCharPos = DoubleStream.of(upperBorder).mapToInt(toCharPos).toArray();
+        int[] lowerCharPos = DoubleStream.of(lowerBorder).mapToInt(toCharPos).toArray();
+        int[] mindCharPos = DoubleStream.of(mean).mapToInt(toCharPos).toArray();
+
+        for (int x = 0; x < width; x++) {
+            if (upperCharPos[x] > 0 && upperCharPos[x] < height) out[upperCharPos[x]][x] = '-';
+            if (lowerCharPos[x] > 0 && lowerCharPos[x] < height) out[lowerCharPos[x]][x] = '-';
+            if (mindCharPos[x] > 0 && mindCharPos[x] < height) out[mindCharPos[x]][x] = '+';
+        }
+
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < height; i++) {
+            sb.append(out[i]);
+            if (i < 98) {
+                sb.append('\n');
+            } 
+        }
+        return sb.toString();
+    }
+
+}

+ 46 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/Histogram.java

@@ -0,0 +1,46 @@
+package de.jplag.clustering.algorithm;
+
+import java.util.Arrays;
+import java.util.DoubleSummaryStatistics;
+import java.util.stream.DoubleStream;
+
+public class Histogram {
+    
+    private double[] bins;
+    private double[] borders;
+
+    public Histogram(double[] bins, double[] borders) {
+        this.bins = bins;
+        this.borders = borders;
+    }
+
+    public double predict(double x) {
+        int index = Arrays.binarySearch(borders, x);
+        if (index == 0 || index == borders.length) return 0;
+        return bins[index - 1];
+    }
+
+    public static Histogram fit(double[] data) {
+        return fit(data, 30);
+    }
+
+    public static Histogram fit(double[] data, int bins) {
+        DoubleSummaryStatistics stats = DoubleStream.of(data).summaryStatistics();
+        double min = stats.getMin();
+        double max = stats.getMax();
+        double[] binArr = new double[bins]; 
+        for (double v : data) {
+            int bin = Math.min((int) (bins * (v - min) / (max - min)), bins - 1);
+            binArr[bin] += 1;
+        }
+        for (int i = 0; i < bins; i++) {
+            binArr[i] /= data.length;
+        }
+        double[] borders = new double[bins + 1];
+        for (int i = 0; i < bins + 1; i++) {
+            borders[i] = min + i * (max - min) / bins;
+        }
+        return new Histogram(binArr, borders);
+    }
+
+}

+ 163 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/SpectralClustering.java

@@ -0,0 +1,163 @@
+package de.jplag.clustering.algorithm;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.ArrayRealVector;
+import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor;
+import org.apache.commons.math3.linear.DiagonalMatrix;
+import org.apache.commons.math3.linear.EigenDecomposition;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.apache.commons.math3.linear.RealVector;
+import org.apache.commons.math3.ml.clustering.Cluster;
+import org.apache.commons.math3.ml.clustering.Clusterable;
+import org.apache.commons.math3.ml.clustering.Clusterer;
+import org.apache.commons.math3.ml.clustering.KMeansPlusPlusClusterer;
+
+import de.jplag.clustering.IntegerClusteringResult;
+
+public class SpectralClustering implements ClusteringAlgorithm {
+
+    private final ClusteringOptions options;
+
+    public SpectralClustering(ClusteringOptions options) {
+        this.options = options;
+    }
+
+    @Override
+    public Collection<Collection<Integer>> cluster(RealMatrix similarityMatrix) {
+        // Calculate points to cluster according to "On spectral clustering: analysis and an algorithm" by Ng, Jordan & Weiss 2001
+        int N = similarityMatrix.getRowDimension();
+
+        // We don't use the similarity function, we already have some kind of similarity
+        RealMatrix W = similarityMatrix.copy();
+        W.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+            @Override
+            public double visit(int row, int column, double value) {
+                if (row == column) return 0;
+                return similarityMatrix.getEntry(row, column);
+            }
+        });
+
+        DiagonalMatrix D_pow_minus_1_over_2 = new DiagonalMatrix(N);
+        D_pow_minus_1_over_2.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+            @Override
+            public double visit(int row, int column, double value) {
+                if (row != column) return 0;
+                return 1 / Math.sqrt(W.getRowVector(row).getL1Norm());
+            }
+        });
+
+        RealMatrix I = new Array2DRowRealMatrix(N, N);
+        I.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+            @Override
+            public double visit(int row, int column, double value) {
+                return row == column ? 1 : 0;
+            }
+        });
+        RealMatrix L = I.subtract(D_pow_minus_1_over_2.multiply(W).multiply(D_pow_minus_1_over_2));
+        EigenDecomposition ed = new EigenDecomposition(L);
+
+
+        List<Integer> eigenValueIds = new ArrayList<>(N);
+        for (int i = 0; i < N; i++) {
+            eigenValueIds.add(i);
+        }
+        eigenValueIds.sort(Comparator.comparingDouble(ed::getRealEigenvalue));
+
+        // find number of clusters as the multiplicity of eigenvalue 0
+        double eps = 0.05;
+        int minK = Math.max(2, (int) DoubleStream.of(ed.getRealEigenvalues()).filter(x -> x < eps).count());
+        int maxK = (int) Math.ceil(N / 2.0);
+        
+        // Find number of clusters using bayesian optimization
+        RealVector lengthScale = new ArrayRealVector(1, options.kernelBandwidth);
+        BayesianOptimization bo = new BayesianOptimization(new ArrayRealVector(1, minK), new ArrayRealVector(1, maxK), options.minRuns, options.maxRuns, options.GPVariance, lengthScale);
+        //bo.debug = true;
+        BayesianOptimization.OptimizationResult<Collection<Collection<Integer>>> boResult = bo.maximize(r -> {
+            int k = (int) Math.round(r.getEntry(0));
+            k = Math.max(minK, k);
+            k = Math.min(maxK, k);
+            Collection<Collection<Integer>> clustering = cluster(k, N, eigenValueIds, ed);
+            IntegerClusteringResult modularityRes = new IntegerClusteringResult(clustering, similarityMatrix);
+            return new BayesianOptimization.OptimizationResult<>(modularityRes.getWorth((a, b) -> (float) similarityMatrix.getEntry(a, b)), clustering);
+        });
+
+        return boResult.getValue();
+    }
+
+    private Collection<Collection<Integer>> cluster(int k, int n, List<Integer> eigenValueIds, EigenDecomposition ed) {
+        RealMatrix Q = new Array2DRowRealMatrix(n, k);
+        Q.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+           public double visit(int row, int column, double value) {
+               int eigenVectorId = eigenValueIds.get(column);
+               RealVector eigenVector = ed.getEigenvector(eigenVectorId);
+               return eigenVector.getEntry(row);
+           }; 
+        });
+
+        List<ClusterableEigenVector> normRows = IntStream.range(0, n).filter(i -> Q.getRowVector(i).getNorm() > 0).mapToObj(row -> new ClusterableEigenVector(row, Q.getRowVector(row).unitVector())).collect(Collectors.toList());
+        
+        Clusterer<ClusterableEigenVector> clusterer = new KMeansPlusPlusClusterer<>(k, options.maxKMeansIterations);
+        List<? extends Cluster<ClusterableEigenVector>> clusters = clusterer.cluster(normRows);   
+        return clusters.stream().map(cluster -> {
+            return cluster.getPoints().stream().map(x -> x.id).collect(Collectors.toList());
+        }).collect(Collectors.toList());
+    }
+
+    private static class ClusterableEigenVector implements Clusterable {
+        private int id;
+        private double[] eigenVector;
+
+        public ClusterableEigenVector(int id, RealVector eigenVector) {
+            this.id = id;
+            this.eigenVector = eigenVector.toArray();
+        }
+
+        @Override
+        public double[] getPoint() {
+            return eigenVector;
+        }
+    }
+
+    public static class ClusteringOptions {
+        /**
+         * The kernel bandwidth for the matern kernel used in the gaussian process for the automatic search for the number of clusters in spectral clustering.
+         * Affects the runtime and results of the spectral clustering.
+         */
+        public float kernelBandwidth = 20.f;
+    
+        /**
+         * This is the assumed level of noise in the evaluation results of a spectral clustering.
+         * Acts as normalization parameter for the gaussian process.
+         * The default setting works well with similarity scores in the range between zero and one.
+         * Affects the runtime and results of the spectral clustering.
+         */
+        public float GPVariance = 0.05f * 0.05f;
+    
+        /**
+         * The minimal number of runs of the spectral clustering algorithm.
+         * These runs will use predefined numbers of clusters and will not use the bayesian optimization to determine the number of clusters. 
+         */
+        public int minRuns = 5;
+    
+        /**
+         * Maximal number of runs of the spectral clustering algorithm.
+         * The bayesian optimization may be stopped before, when no more maxima of the acquisition-function are found.
+         */
+        public int maxRuns = 50;
+    
+        /**
+         * Maximum number of iterations of the kMeans clustering per run of the spectral clustering algorithm.
+         */
+        public int maxKMeansIterations = 200;
+
+    }
+    
+}

+ 186 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/TopDownHierarchicalClustering.java

@@ -0,0 +1,186 @@
+package de.jplag.clustering.algorithm;
+
+import java.util.AbstractList;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.stream.Collectors;
+
+import org.apache.commons.math3.linear.RealMatrix;
+
+public class TopDownHierarchicalClustering implements ClusteringAlgorithm {
+
+    private ClusteringOptions options;
+
+    public TopDownHierarchicalClustering(ClusteringOptions options) {
+        this.options = options;
+    }
+
+    @Override
+    public Collection<Collection<Integer>> cluster(RealMatrix similarityMatrix) {
+        int N = similarityMatrix.getRowDimension();
+        // all clusters that do not have a parent yet
+        HashSet<Cluster> clusters = new HashSet<>(N);
+        // calculated similarities. Might contain connections to already visited clusters, those need to be ignored.
+        PriorityQueue<ClusterConnection> similarities;
+
+        {
+            // initialization
+
+            ArrayList<Cluster> initialClusters = new ArrayList<>(N);
+            for (int i = 0; i < N; i++) {
+                Cluster cluster = new Cluster(Collections.singletonList(i));
+                initialClusters.add(cluster);
+                clusters.add(cluster);
+            }
+
+            ArrayList<ClusterConnection> initialSimilarities = new ArrayList<>(N * (N - 1) / 2);
+
+            for (int leftIndex = 0; leftIndex < initialClusters.size(); leftIndex++) {
+                Cluster leftCluster = initialClusters.get(leftIndex);
+                for (int rightIndex = leftIndex + 1; rightIndex < initialClusters.size(); rightIndex++) {
+                    Cluster rightCluster = initialClusters.get(rightIndex);
+                    initialSimilarities.add(new ClusterConnection(leftCluster, rightCluster, (float) similarityMatrix.getEntry(leftIndex, rightIndex)));
+                }
+            }
+
+            similarities = new PriorityQueue<>(initialSimilarities);
+        }
+
+        while (clusters.size() > 1) {
+            ClusterConnection nearest = similarities.poll();
+            if (!(clusters.contains(nearest.left) && clusters.contains(nearest.right))) {
+                // One cluster already part of another cluster
+                continue;
+            }
+            if (nearest.similarity < options.minimalSimilarity) {
+                break;
+            }
+            clusters.remove(nearest.left);
+            clusters.remove(nearest.right);
+            Cluster combined = new Cluster(new MergedList(nearest.left.getSubmissions(), nearest.right.getSubmissions()));
+            for (Cluster otherCluster : clusters) {
+                similarities.add(new ClusterConnection(combined, otherCluster, similarityMatrix));
+            }
+            clusters.add(combined);
+        }
+
+        return clusters.stream().map(Cluster::getSubmissions).collect(Collectors.toList());
+    }
+
+    private float clusterSimilarity(List<Integer> leftCluster, List<Integer> rightCluster, RealMatrix similarityMatrix) {
+        float similarity = 0;
+        switch (options.similarity) {
+            case MIN:
+            similarity = Float.MAX_VALUE;
+            break;
+            case MAX:
+            similarity = -Float.MAX_VALUE;
+            break;
+            case AVERAGE:
+            similarity = 0;
+            break;
+        }
+
+        for (int leftIndex = 0; leftIndex < leftCluster.size(); leftIndex++) {
+            int leftSubmission = leftCluster.get(leftIndex);
+            for (int rightIndex = 0; rightIndex < rightCluster.size(); rightIndex++) {
+                float submissionSimilarity = (float) similarityMatrix.getEntry(leftSubmission, rightCluster.get(rightIndex));
+                switch (options.similarity) {
+                    case MIN:
+                    similarity = Math.min(similarity, submissionSimilarity);
+                    break;
+                    case MAX:
+                    similarity = Math.max(similarity, submissionSimilarity);
+                    break;
+                    case AVERAGE:
+                    similarity += submissionSimilarity;
+                }
+            }
+        }
+    
+        
+        if (options.similarity == InterClusterSimilarity.AVERAGE) {
+            similarity /= leftCluster.size() * rightCluster.size();
+        }
+        return similarity;
+    }
+
+    public static class ClusteringOptions {
+        public float minimalSimilarity = 0.1f;
+        public InterClusterSimilarity similarity = InterClusterSimilarity.AVERAGE; 
+    }
+
+    public static enum InterClusterSimilarity {
+        MIN,
+        MAX,
+        AVERAGE;
+    }
+
+    private class ClusterConnection implements Comparable<ClusterConnection> {
+
+        private Cluster left;
+        private Cluster right;
+        private float similarity;
+
+        public ClusterConnection(Cluster left, Cluster right, RealMatrix similarity) {
+            this(left, right, clusterSimilarity(left.submissions, right.submissions, similarity));
+        }
+
+        public ClusterConnection(Cluster left, Cluster right, float similarity) {
+            this.left = left;
+            this.right = right;
+            this.similarity = similarity;
+        }
+
+        @Override
+        public int compareTo(ClusterConnection other) {
+            return (int) Math.signum(other.similarity - similarity);
+        }
+        
+    }
+
+    private class Cluster {
+        private List<Integer> submissions;
+
+        public Cluster(List<Integer> submissions) {
+            this.submissions = submissions;
+        }
+
+        public List<Integer> getSubmissions() {
+            return submissions;
+        }
+        
+    }
+
+    private class MergedList extends AbstractList<Integer> {
+
+        private List<Integer> left, right;
+        private int size;
+
+        public MergedList(List<Integer> left, List<Integer> right) {
+            this.left = left;
+            this.right = right;
+            size = left.size() + right.size();
+        }
+
+        @Override
+        public Integer get(int index) {
+            if (index < left.size()) {
+                return left.get(index);
+            } else {
+                return right.get(index - left.size());
+            }
+        }
+
+        @Override
+        public int size() {
+            return size;
+        }
+        
+    }
+    
+}

+ 55 - 0
jplag/src/main/java/de/jplag/clustering/preprocessors/CdfPreprocessor.java

@@ -0,0 +1,55 @@
+package de.jplag.clustering.preprocessors;
+
+import java.util.Collection;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor;
+import org.apache.commons.math3.linear.DefaultRealMatrixPreservingVisitor;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.apache.commons.math3.random.EmpiricalDistribution;
+
+import de.jplag.clustering.Preprocessor;
+
+/**
+ * Multiplies entries of the similarity matrix by their cumulative probability.
+ *  - Weights that are very low will be (close to) zero
+ *  - Weights that are very high will be (close to) unchanged
+ */
+public class CdfPreprocessor implements Preprocessor{
+
+    private PreprocessorHelper helper = new PreprocessorHelper();
+
+    @Override
+    public double[][] preprocessSimilarities(double[][] similarityMatrix) {
+        RealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, true); 
+        int connections = (similarity.getColumnDimension() * (similarity.getColumnDimension() - 1)) / 2;
+        EmpiricalDistribution dist = new EmpiricalDistribution(Math.max(100, connections / 100));
+        double[] allWeights = new double[connections];
+        similarity.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
+
+            int index = 0;
+
+            @Override
+            public void visit(int row, int column, double value) {
+                // collect upper triangle
+                if (row > column) {
+                    allWeights[this.index++] = value;
+                }
+            }
+        });
+        dist.load(allWeights);
+        similarity.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+            @Override
+            public double visit(int row, int column, double value) {
+                return dist.cumulativeProbability(value) * value;
+            }
+        });
+        return helper.removeDisconnectedEntries(similarity.getData());
+    }
+
+    @Override
+    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+        return helper.postProcessResult(result);
+    }
+    
+}

+ 50 - 0
jplag/src/main/java/de/jplag/clustering/preprocessors/PercentileThresholdProcessor.java

@@ -0,0 +1,50 @@
+package de.jplag.clustering.preprocessors;
+
+import java.util.Collection;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.DefaultRealMatrixPreservingVisitor;
+import org.apache.commons.math3.stat.descriptive.rank.Percentile;
+import org.apache.commons.math3.stat.descriptive.rank.Percentile.EstimationType;
+
+import de.jplag.clustering.Preprocessor;
+
+public class PercentileThresholdProcessor implements Preprocessor {
+
+    private float percentile; 
+    private ThresholdPreprocessor tp;
+
+    public PercentileThresholdProcessor(float percentile) {
+        this.percentile = percentile;
+    }
+
+    @Override
+    public double[][] preprocessSimilarities(double[][] similarityMatrix) {
+        Array2DRowRealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, false); 
+        Percentile p = new Percentile().withEstimationType(EstimationType.R_2);
+        int connections = (similarity.getColumnDimension() * (similarity.getColumnDimension() - 1)) / 2;
+        double[] allWeights = new double[connections];
+        similarity.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
+
+            int index = 0;
+
+            @Override
+            public void visit(int row, int column, double value) {
+                // collect upper triangle
+                if (row > column) {
+                    allWeights[this.index++] = value;
+                }
+            }
+        });
+        double threshold = p.evaluate(allWeights, percentile);
+        tp = new ThresholdPreprocessor(threshold);
+
+        return tp.preprocessSimilarities(similarityMatrix);
+    }
+
+    @Override
+    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+        return tp.postProcessResult(result);
+    }
+    
+}

+ 38 - 0
jplag/src/main/java/de/jplag/clustering/preprocessors/ThresholdPreprocessor.java

@@ -0,0 +1,38 @@
+package de.jplag.clustering.preprocessors;
+
+import java.util.Collection;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor;
+import org.apache.commons.math3.linear.RealMatrix;
+
+import de.jplag.clustering.Preprocessor;
+
+public class ThresholdPreprocessor implements Preprocessor {
+
+    private double threshold;
+    private PreprocessorHelper helper = new PreprocessorHelper();
+
+    public ThresholdPreprocessor(double threshold) {
+        this.threshold = threshold;
+    }
+
+    @Override
+    public double[][] preprocessSimilarities(double[][] similarityMatrix) {
+        RealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, true);
+        similarity.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
+            @Override
+            public double visit(int row, int column, double value) {
+                return value >= threshold ? value : 0;
+            }
+        });
+        return helper.removeDisconnectedEntries(similarity.getData());
+    }
+
+    @Override
+    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+        return helper.postProcessResult(result);
+    }
+    
+    
+}

+ 194 - 0
jplag/src/main/java/de/jplag/options/JPlagOptions.java

@@ -6,6 +6,9 @@ import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 
 import de.jplag.Language;
+import de.jplag.clustering.Algorithms;
+import de.jplag.clustering.Preprocessors;
+import de.jplag.clustering.algorithm.TopDownHierarchicalClustering;
 import de.jplag.strategy.ComparisonMode;
 
 public class JPlagOptions {
@@ -91,6 +94,84 @@ public class JPlagOptions {
      */
     private Verbosity verbosity;
 
+    /**
+     * This similarity metric is used for clustering.
+     */
+    private SimilarityMetric clusteringSimilarityMetric = SimilarityMetric.MAX;
+
+    /**
+     * The kernel bandwidth for the matern kernel used in the gaussian process for the automatic search for the number of clusters in spectral clustering.
+     * Affects the runtime and results of the spectral clustering.
+     */
+    private float clusteringSpectralKernelBandwidth = 20.f;
+
+    /**
+     * This is the assumed level of noise in the evaluation results of a spectral clustering.
+     * Acts as normalization parameter for the gaussian process.
+     * The default setting works well with similarity scores in the range between zero and one.
+     * Affects the runtime and results of the spectral clustering.
+     */
+    private float clusteringSpectralGPVariance = 0.05f * 0.05f;
+
+    /**
+     * The minimal number of runs of the spectral clustering algorithm.
+     * These runs will use predefined numbers of clusters and will not use the bayesian optimization to determine the number of clusters. 
+     */
+    private int clusteringSpectralMinRuns = 5;
+
+    /**
+     * Maximal number of runs of the spectral clustering algorithm.
+     * The bayesian optimization may be stopped before, when no more maxima of the acquisition-function are found.
+     */
+    private int clusteringSpectralMaxRuns = 50;
+
+    /**
+     * Maximum number of iterations of the kMeans clustering per run of the spectral clustering algorithm.
+     */
+    private int clusteringSpectralMaxKMeansIterationPerRun = 200;
+
+    /**
+     * Remove clusters that are evaluated as especially bad from the final set of clusters.
+     */
+    private boolean clusteringPruneBadClusters = true;
+
+    /**
+     * Preprocessing for the similarity values before clustering.
+     * This is mandatory for spectral clustering and optional for agglomerative clustering.
+     */
+    private Preprocessors clusteringPreprocessor = Preprocessors.CDF;
+
+    /**
+     * Sets up to which similarity the threshold preprocessor zeroes out the similarities.
+     */
+    private float clusteringPreprocessorThreshold = 0.2f;
+
+    /**
+     * Sets up to which percentile of the percentile preprocessor zeroes out the similarities.
+     */
+    private float clusteringPreprocessorPercentile = 0.5f;
+
+    /**
+     * Agglomerative clustering will merge clusters that have a similarity higher than this threshold.
+     */
+    private float clusteringAgglomerativeThreshold = 0.2f;
+
+    /**
+     * Similarity measure between clusters in agglomerative clustering. 
+     */
+    private TopDownHierarchicalClustering.InterClusterSimilarity clusteringAgglomerativeInterClusterSimilarity = TopDownHierarchicalClustering.InterClusterSimilarity.AVERAGE;
+
+    /**
+     * The clustering algorithm to use.
+     */
+    private Algorithms clusteringAlgorithm = Algorithms.SPECTRAL;
+
+    /**
+     * If clustering should be performed.
+     */
+    private boolean clusteringDoClustering = true;
+
+
     /**
      * Constructor with required attributes.
      */
@@ -182,6 +263,62 @@ public class JPlagOptions {
         return similarityMetric;
     }
 
+    public SimilarityMetric getClusteringSimilarityMetric() {
+        return clusteringSimilarityMetric;
+    }
+
+    public float getClusteringSpectralKernelBandwidth() {
+        return clusteringSpectralKernelBandwidth;
+    }
+
+    public float getClusteringSpectralGPVariance() {
+        return clusteringSpectralGPVariance;
+    }
+
+    public int getClusteringSpectralMinRuns() {
+        return clusteringSpectralMinRuns;
+    }
+
+    public int getClusteringSpectralMaxRuns() {
+        return clusteringSpectralMaxRuns;
+    }
+
+    public int getClusteringSpectralMaxKMeansIterationPerRun() {
+        return clusteringSpectralMaxKMeansIterationPerRun;
+    }
+
+    public boolean isClusteringPruneBadClusters() {
+        return clusteringPruneBadClusters;
+    }
+
+    public float getClusteringAgglomerativeThreshold() {
+        return clusteringAgglomerativeThreshold;
+    }
+
+    public Preprocessors getClusteringPreprocessor() {
+        return clusteringPreprocessor;
+    }
+
+    public boolean isClustering() {
+        return clusteringDoClustering;
+    }
+
+    public Algorithms getClusteringAlgorithm() {
+        return clusteringAlgorithm;
+    }
+
+    public TopDownHierarchicalClustering.InterClusterSimilarity getClusteringAgglomerativeInterClusterSimilarity() {
+        return clusteringAgglomerativeInterClusterSimilarity;
+    }
+
+    public float getClusteringPreprocessorThreshold() {
+        return clusteringPreprocessorThreshold;
+    }
+
+    public float getClusteringPreprocessorPercentile() {
+        return clusteringPreprocessorPercentile;
+    }
+
     public void setLanguage(Language language) {
         this.language = language;
     }
@@ -253,4 +390,61 @@ public class JPlagOptions {
     public void setSimilarityMetric(SimilarityMetric similarityMetric) {
         this.similarityMetric = similarityMetric;
     }
+
+    public void setClusteringSimilarityMetric(SimilarityMetric clusteringSimilarityMetric) {
+        this.clusteringSimilarityMetric = clusteringSimilarityMetric;
+    }
+
+    public void setClusteringSpectralKernelBandwidth(float clusteringSpectralKernelBandwidth) {
+        this.clusteringSpectralKernelBandwidth = clusteringSpectralKernelBandwidth;
+    }
+
+    public void setClusteringSpectralGPVariance(float clusteringSpectralGPVariance) {
+        this.clusteringSpectralGPVariance = clusteringSpectralGPVariance;
+    }
+
+    public void setClusteringSpectralMinRuns(int clusteringSpectralMinRuns) {
+        this.clusteringSpectralMinRuns = clusteringSpectralMinRuns;
+    }
+
+    public void setClusteringSpectralMaxRuns(int clusteringSpectralMaxRuns) {
+        this.clusteringSpectralMaxRuns = clusteringSpectralMaxRuns;
+    }
+
+    public void setClusteringSpectralMaxKMeansIterationPerRun(int clusteringSpectralMaxKMeansIterationPerRun) {
+        this.clusteringSpectralMaxKMeansIterationPerRun = clusteringSpectralMaxKMeansIterationPerRun;
+    }
+
+    public void setClusteringPruneBadClusters(boolean clusteringPruneBadClusters) {
+        this.clusteringPruneBadClusters = clusteringPruneBadClusters;
+    }
+
+    public void setClusteringPreprocessor(Preprocessors clusteringPreprocessor) {
+        this.clusteringPreprocessor = clusteringPreprocessor;
+    }
+
+    public void setClusteringAgglomerativeThreshold(float clusteringAgglomerativeThreshold) {
+        this.clusteringAgglomerativeThreshold = clusteringAgglomerativeThreshold;
+    }
+
+    public void setClusteringAgglomerativeInterClusterSimilarity(
+            TopDownHierarchicalClustering.InterClusterSimilarity clusteringAgglomerativeInterClusterSimilarity) {
+        this.clusteringAgglomerativeInterClusterSimilarity = clusteringAgglomerativeInterClusterSimilarity;
+    }
+
+    public void setClusteringAlgorithm(Algorithms clusteringAlgorithm) {
+        this.clusteringAlgorithm = clusteringAlgorithm;
+    }
+
+    public void setClustering(boolean clustering) {
+        this.clusteringDoClustering = clustering;
+    }
+
+    public void setClusteringPreprocessorThreshold(float clusteringPreprocessorThreshold) {
+        this.clusteringPreprocessorThreshold = clusteringPreprocessorThreshold;
+    }
+
+    public void setClusteringPreprocessorPercentile(float clusteringPreprocessorPercentile) {
+        this.clusteringPreprocessorPercentile = clusteringPreprocessorPercentile;
+    }
 }

+ 8 - 2
jplag/src/main/java/de/jplag/options/SimilarityMetric.java

@@ -4,10 +4,11 @@ import java.util.function.Function;
 
 import de.jplag.JPlagComparison;
 
-public enum SimilarityMetric {
+public enum SimilarityMetric implements Function<JPlagComparison, Float> {
     AVG(it -> it.similarity()),
     MIN(it -> it.minimalSimilarity()),
-    MAX(it -> it.maximalSimilarity());
+    MAX(it -> it.maximalSimilarity()),
+    INTERSECTION(it -> (float) it.getNumberOfMatchedTokens());
 
     private final Function<JPlagComparison, Float> similarityFunction;
 
@@ -18,4 +19,9 @@ public enum SimilarityMetric {
     public boolean isAboveThreshold(JPlagComparison comparison, float similarityThreshold) {
         return similarityFunction.apply(comparison) >= similarityThreshold;
     }
+
+    @Override
+    public Float apply(JPlagComparison comparison) {
+        return similarityFunction.apply(comparison);
+    }
 }

+ 257 - 0
jplag/src/test/java/de/jplag/clustering/ClusteringTest.java

@@ -0,0 +1,257 @@
+package de.jplag.clustering;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.List;
+import java.util.Scanner;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.junit.Test;
+import org.mockito.invocation.InvocationOnMock;
+
+import de.jplag.JPlagComparison;
+import de.jplag.Submission;
+import de.jplag.clustering.ClusteringResult.Cluster;
+import de.jplag.clustering.algorithm.ClusteringAlgorithm;
+import de.jplag.clustering.algorithm.SpectralClustering;
+import de.jplag.clustering.algorithm.TopDownHierarchicalClustering;
+import de.jplag.clustering.preprocessors.CdfPreprocessor;
+
+public class ClusteringTest {
+    
+    @Test
+    public void testClustering() {
+        List<Submission> submissions = IntStream.range(0, 4).mapToObj(x -> mock(Submission.class)).collect(Collectors.toList());
+        List<JPlagComparison> comparisons = new ArrayList<>(6);
+        for (int i = 0; i < submissions.size(); i++) {
+            for (int j = i + 1; j < submissions.size(); j++) {
+                JPlagComparison comparison = mock(JPlagComparison.class);
+                when(comparison.getFirstSubmission()).thenReturn(submissions.get(i));
+                when(comparison.getSecondSubmission()).thenReturn(submissions.get(j));
+                comparisons.add(comparison);
+            }
+        }
+
+        // Mock algorithm that returns everything in a single cluster
+        ClusteringAlgorithm algorithm = mock(ClusteringAlgorithm.class);
+        when(algorithm.cluster(any(RealMatrix.class))).then((InvocationOnMock invocation) -> {
+            RealMatrix arg = invocation.getArgument(0);
+            Collection<Collection<Integer>> result = List.of(IntStream.range(0, arg.getRowDimension()).boxed().collect(Collectors.toList()));
+            return result;
+        });
+
+        ClusteringAdapter clustering = new ClusteringAdapter(comparisons, x -> 0.f);
+        ClusteringResult<Submission> clusteringResult = clustering.doClustering(algorithm);
+
+        Collection<Collection<Submission>> expectedResult = List.of(submissions);
+
+        assertEquals(expectedResult, clusteringResult.getClusters().stream().map(Cluster::getMembers).collect(Collectors.toList()));
+    }
+
+    private String str(float f) {
+        return String.format("%.4f", f);
+    }
+
+    private float harmonicMean(float a, float b) {
+        return 2 * a * b / (a + b);
+    }
+
+    @Test
+    public void aClusteringOld() throws FileNotFoundException, URISyntaxException {
+        URL url = getClass().getClassLoader().getResource("de/jplag/PseudonymizedReports/alt/C_1000_matches_max.csv");
+        if (url == null) {
+            throw new FileNotFoundException();
+        }
+        File file = new File(url.toURI());
+        ReadResult r = readOldCsv(file);
+        Preprocessor preprocessor = new CdfPreprocessor();
+        RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(preprocessor.preprocessSimilarities(r.similarity.getData()));
+
+        /*
+        TopDownHierachicalClustering.ClusteringOptions options = new TopDownHierachicalClustering.ClusteringOptions();
+        options.minimalSimilarity = 0.15f;
+        options.similarity = TopDownHierachicalClustering.InterClusterSimilarity.AVERAGE;
+        ClusteringAlgorithm clusteringAlg = new TopDownHierachicalClustering(options);
+        */
+        
+        SpectralClustering clusteringAlg = new SpectralClustering(new SpectralClustering.ClusteringOptions());
+        Collection<Collection<Integer>> clustering = clusteringAlg.cluster(clusteringSimilarity);
+        clustering = preprocessor.postProcessResult(clustering);
+        ClusteringResult<Integer> mRes = new IntegerClusteringResult(clustering, r.similarity);
+        List<Cluster<Integer>> clusters = new ArrayList<>(mRes.getClusters());
+        clusters.sort(Comparator.comparingDouble(c -> -harmonicMean(c.getCommunityStrengthPerConnection(), avgSimilarity(new ArrayList<>(c.getMembers()), r.similarity))));
+
+        System.out.println("cs\tncsm\tavgSim\tcombined\tmembers");
+        for (Cluster<Integer> c : clusters) {
+            float ncsm = c.getCommunityStrengthPerConnection();
+            float avgSim = c.avgSimilarity((a, b) -> (float) r.similarity.getEntry(a, b));
+            float combined = harmonicMean(ncsm, avgSim);
+            System.out.println(str(c.getCommunityStrength()) + "\t" + str(ncsm) + "\t" + str(avgSim) + "\t" + str(combined) + "\t" + c.getMembers().stream().map(r.mapping::unmap).collect(Collectors.toList()));
+        }
+        System.out.println("Community Strength: " + mRes.getCommunityStrength());
+        System.out.println("Clusters: " + clusters.size());
+    }
+
+    @Test
+    public void aClusteringNew() throws FileNotFoundException, URISyntaxException {
+        URL url = getClass().getClassLoader().getResource("de/jplag/PseudonymizedReports/neu/B_matches_avg.csv");
+        if (url == null) {
+            throw new FileNotFoundException();
+        }
+        File file = new File(url.toURI());
+        ReadResult r = readNewCsv(file);
+        RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(new CdfPreprocessor().preprocessSimilarities(r.similarity.getData()));
+
+        /*
+        TopDownHierarchicalClustering.ClusteringOptions options = new TopDownHierarchicalClustering.ClusteringOptions();
+        options.minimalSimilarity = 0.3f;
+        options.similarity = TopDownHierarchicalClustering.InterClusterSimilarity.AVERAGE;
+        ClusteringAlgorithm clusteringAlg = new TopDownHierarchicalClustering(options);
+        */
+        
+        SpectralClustering clusteringAlg = new SpectralClustering(new SpectralClustering.ClusteringOptions());
+        
+        Collection<Collection<Integer>> clustering = clusteringAlg.cluster(clusteringSimilarity);
+        ClusteringResult<Integer> mRes = new IntegerClusteringResult(clustering, r.similarity);
+        List<Cluster<Integer>> clusters = new ArrayList<>(mRes.getClusters());
+        clusters.sort(Comparator.comparingDouble(c -> -harmonicMean(c.getNormalizedCommunityStrengthPerConnection(), avgSimilarity(new ArrayList<>(c.getMembers()), r.similarity))));
+
+        System.out.println("cs\tncsm\tavgSim\tcombined\tmembers");
+        for (Cluster<Integer> c : clusters) {
+            if (c.isBadCluster()) continue;
+            float ncsm = c.getNormalizedCommunityStrengthPerConnection();
+            float avgSim = c.avgSimilarity((a, b) -> (float) r.similarity.getEntry(a, b));
+            float combined = harmonicMean(ncsm, avgSim);
+            System.out.println(str(c.getCommunityStrength()) + "\t" + str(ncsm) + "\t" + str(avgSim) + "\t" + str(combined) + "\t" + c.getMembers().stream().map(r.mapping::unmap).collect(Collectors.toList()));
+        }
+        System.out.println("Community Strength: " + mRes.getCommunityStrength());
+        System.out.println("Clusters: " + clusters.size());
+    }
+
+    private float avgSimilarity(List<Integer> submissions, RealMatrix similarity) {
+        float similaritySum = 0;
+        int comps = 0;
+
+        for (int i = 0; i < submissions.size(); i++) {
+            for (int j = i + 1; j < submissions.size(); j++) {
+                similaritySum += similarity.getEntry(submissions.get(i), submissions.get(j));
+                comps++;
+            }
+        }
+
+        return similaritySum / comps;
+    }
+
+    private static class ReadComparison {
+        int left;
+        int right;
+        float similarity;
+    }
+
+    private static class ReadResult {
+        IntegerMapping<String> mapping;
+        RealMatrix similarity;
+    }
+
+    private static ReadResult readNewCsv(File fileName) throws FileNotFoundException {
+        IntegerMapping<String> mapping = new IntegerMapping<>(512);
+        List<ReadComparison> comparisons = new ArrayList<>(512);
+        try (CSVReader reader = new CSVReader(fileName, ";")) {
+            while (reader.hasNext()) {
+                List<String> records = reader.next();
+                if (records.isEmpty()) continue;
+                String leftStudent = records.get(1);
+                String rightStudent = records.get(2);
+                String similarity = records.get(3);
+                ReadComparison comparison = new ReadComparison();
+                comparison.left = mapping.map(leftStudent);
+                comparison.right = mapping.map(rightStudent);
+                comparison.similarity = Float.parseFloat(similarity) / 100;
+                comparisons.add(comparison);
+            }
+        }
+        RealMatrix matrix = new Array2DRowRealMatrix(mapping.size(), mapping.size());
+        for (ReadComparison comparison : comparisons) {
+            matrix.setEntry(comparison.left, comparison.right, comparison.similarity);
+            matrix.setEntry(comparison.right, comparison.left, comparison.similarity);
+        }
+        ReadResult r = new ReadResult();
+        r.similarity = matrix;
+        r.mapping = mapping;
+        return r;
+    }
+
+    private static ReadResult readOldCsv(File fileName) throws FileNotFoundException {
+        IntegerMapping<String> mapping = new IntegerMapping<>(512);
+        List<ReadComparison> comparisons = new ArrayList<>(512);
+        try (CSVReader reader = new CSVReader(fileName, ";")) {
+            while (reader.hasNext()) {
+                List<String> records = reader.next();
+                if (records.isEmpty()) continue;
+                Deque<String> stuff = new ArrayDeque<>(records);
+                String leftStudent = stuff.removeFirst();
+                int leftID = mapping.map(leftStudent);
+                while (stuff.size() >= 3) {
+                    ReadComparison comparison = new ReadComparison();
+                    comparison.left = leftID;
+                    stuff.removeFirst(); // comparison ID not needed
+                    String rightStudent = stuff.removeFirst();
+                    String similarity = stuff.removeFirst();
+                    comparison.right = mapping.map(rightStudent);
+                    comparison.similarity = Float.parseFloat(similarity) / 100;
+                    comparisons.add(comparison);
+                }
+            }
+        }
+        RealMatrix matrix = new Array2DRowRealMatrix(mapping.size(), mapping.size());
+        for (ReadComparison comparison : comparisons) {
+            matrix.setEntry(comparison.left, comparison.right, comparison.similarity);
+            matrix.setEntry(comparison.right, comparison.left, comparison.similarity);
+        }
+        ReadResult r = new ReadResult();
+        r.similarity = matrix;
+        r.mapping = mapping;
+        return r;
+    }
+
+    private static class CSVReader implements AutoCloseable {
+        private String delimiter;
+        private Scanner scanner;
+        private CSVReader(File fileName, String delimiter) throws FileNotFoundException {
+            this.delimiter = delimiter;
+            scanner = new Scanner(fileName);
+        }
+
+        @Override
+        public void close() {
+            scanner.close();
+        }
+
+        List<String> next() {
+            String line = scanner.nextLine();
+            String[] records = line.split(delimiter);
+            return Arrays.asList(records);
+        }
+
+        boolean hasNext() {
+            return scanner.hasNextLine();
+        }
+    }
+
+}

+ 37 - 0
jplag/src/test/java/de/jplag/clustering/algorithm/GaussianProcessTest.java

@@ -0,0 +1,37 @@
+package de.jplag.clustering.algorithm;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.math3.linear.ArrayRealVector;
+import org.apache.commons.math3.linear.RealVector;
+import org.junit.Test;
+
+public class GaussianProcessTest {
+    
+    @Test
+    public void noisyLinearFunction() {
+        List<RealVector> X = new ArrayList<>();
+        double[] Y = new double[20];
+        int idx = 0;
+        for (int i = 0; i < 10; i++) {
+            RealVector x = new ArrayRealVector(1);
+            x.setEntry(0, i);
+            X.add(x);
+            X.add(x);
+            Y[idx++] = i + Math.random() - 0.5;
+            Y[idx++] = i + Math.random() - 0.5;
+        }
+        GaussianProcess gp = GaussianProcess.fit(X, Y, 1 / 12.0, true);
+        for (int i = 0; i < 19; i++) {
+            RealVector vx = new ArrayRealVector(1);
+            double x = i / 2.0;
+            vx.setEntry(0, x);
+            double[] prediction = gp.predictWidthStd(vx);
+            assertTrue("The prediction error can't be greater that the random value added", Math.abs(prediction[0] - x) < 0.5);
+            assertTrue("The standard deviation must be greater than 0", prediction[1] > 0);
+        }
+    }
+}

+ 54 - 0
jplag/src/test/java/de/jplag/clustering/algorithm/TopDownHierarchicalClusteringTest.java

@@ -0,0 +1,54 @@
+package de.jplag.clustering.algorithm;
+
+import de.jplag.clustering.algorithm.TopDownHierarchicalClustering.ClusteringOptions;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.apache.commons.math3.linear.Array2DRowRealMatrix;
+import org.apache.commons.math3.linear.RealMatrix;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TopDownHierarchicalClusteringTest {
+    TopDownHierarchicalClustering clustering;
+
+    @Before
+    public void init() {
+        ClusteringOptions options = new ClusteringOptions();
+        options.minimalSimilarity = 0.4f;
+        clustering = new TopDownHierarchicalClustering(options);
+    }
+
+    @Test
+    public void test() {
+        RealMatrix similarity = new Array2DRowRealMatrix(4, 4);
+        for (int i = 0; i < 4; i++) {
+            similarity.setEntry(i, i, 1);
+        }
+        // These are similar
+        similarity.setEntry(0, 1, 0.5f);
+        similarity.setEntry(2, 3, 0.5f);
+
+        // Others are dissimilar
+        similarity.setEntry(0, 2, 0.1f);
+        similarity.setEntry(0, 3, 0.1f);
+        similarity.setEntry(1, 2, 0.1f);
+        similarity.setEntry(1, 3, 0.1f);
+
+        Collection<Collection<Integer>> result = clustering.cluster(similarity);
+        assertTrue("There should be two clusters", result.size() == 2);
+        assertTrue("should contain all original numbers", result.stream().reduce(new ArrayList<Integer>(), (a, b) -> {
+            ArrayList<Integer> combined = new ArrayList<>();
+            combined.addAll(a);
+            combined.addAll(b);
+            return combined;
+        }).size() == 4);
+        assertTrue("Should be clustered as {0,1}, {2,3}", result.stream().allMatch(cluster -> {
+            return cluster.size() == 2 && cluster.stream().reduce((a, b) -> Math.abs(a - b)).orElse(0) == 1; 
+        }) && result.stream().map(Collection::size).reduce((a, b) -> a + b).orElse(0) == 4);
+
+    }
+}

+ 1 - 0
jplag/src/test/resources/de/jplag/PseudonymizedReports

@@ -0,0 +1 @@
+Subproject commit 26e1c3f4f7b18f3a4b7e210ac3dffd70b997961e