Simon Ding 4 anni fa
parent
commit
f3fb6000ed
28 ha cambiato i file con 504 aggiunte e 534 eliminazioni
  1. 114 114
      jplag/pom.xml
  2. 4 2
      jplag/src/main/java/de/jplag/CLI.java
  3. 2 3
      jplag/src/main/java/de/jplag/CliGroupHelper.java
  4. 49 28
      jplag/src/main/java/de/jplag/CommandLineArgument.java
  5. 1 1
      jplag/src/main/java/de/jplag/JPlag.java
  6. 2 1
      jplag/src/main/java/de/jplag/clustering/Algorithms.java
  7. 6 6
      jplag/src/main/java/de/jplag/clustering/ClusteringAdapter.java
  8. 5 6
      jplag/src/main/java/de/jplag/clustering/ClusteringFactory.java
  9. 1 2
      jplag/src/main/java/de/jplag/clustering/ClusteringOptions.java
  10. 19 38
      jplag/src/main/java/de/jplag/clustering/ClusteringResult.java
  11. 6 4
      jplag/src/main/java/de/jplag/clustering/IntegerClusteringResult.java
  12. 1 1
      jplag/src/main/java/de/jplag/clustering/IntegerMapping.java
  13. 1 0
      jplag/src/main/java/de/jplag/clustering/Preprocessor.java
  14. 4 1
      jplag/src/main/java/de/jplag/clustering/Preprocessors.java
  15. 19 19
      jplag/src/main/java/de/jplag/clustering/algorithm/AgglomerativeClustering.java
  16. 155 202
      jplag/src/main/java/de/jplag/clustering/algorithm/BFGS.java
  17. 10 15
      jplag/src/main/java/de/jplag/clustering/algorithm/BayesianOptimization.java
  18. 24 18
      jplag/src/main/java/de/jplag/clustering/algorithm/GaussianProcess.java
  19. 35 31
      jplag/src/main/java/de/jplag/clustering/algorithm/SpectralClustering.java
  20. 5 6
      jplag/src/main/java/de/jplag/clustering/preprocessors/CdfPreprocessor.java
  21. 3 3
      jplag/src/main/java/de/jplag/clustering/preprocessors/PercentileThresholdProcessor.java
  22. 1 2
      jplag/src/main/java/de/jplag/clustering/preprocessors/ThresholdPreprocessor.java
  23. 1 1
      jplag/src/main/java/de/jplag/options/JPlagOptions.java
  24. 1 1
      jplag/src/test/java/de/jplag/cli/ClusteringTest.java
  25. 27 21
      jplag/src/test/java/de/jplag/clustering/ClusteringTest.java
  26. 3 3
      jplag/src/test/java/de/jplag/clustering/algorithm/AgglomerativeClusteringTest.java
  27. 4 4
      jplag/src/test/java/de/jplag/clustering/algorithm/BayesianOptimizationTest.java
  28. 1 1
      jplag/src/test/java/de/jplag/clustering/algorithm/GaussianProcessTest.java

+ 114 - 114
jplag/pom.xml

@@ -1,114 +1,114 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
-    <modelVersion>4.0.0</modelVersion>
-
-    <parent>
-        <groupId>de.jplag</groupId>
-        <artifactId>aggregator</artifactId>
-        <version>3.1.0-SNAPSHOT</version>
-    </parent>
-    <artifactId>jplag</artifactId>
-
-    <dependencies>
-        <dependency>
-            <groupId>net.sourceforge.argparse4j</groupId>
-            <artifactId>argparse4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>com.github.stefanbirkner</groupId>
-            <artifactId>system-rules</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-math3</artifactId>
-            <version>3.6.1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.mockito</groupId>
-            <artifactId>mockito-core</artifactId>
-            <version>4.0.0</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>frontend-utils</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>text</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>java</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>python-3</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>csharp-1.2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>cpp</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>scheme</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>de.jplag</groupId>
-            <artifactId>chars</artifactId>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <resources>
-            <resource>
-                <filtering>true</filtering>
-                <directory>src/main/resources</directory>
-            </resource>
-
-            <resource>
-                <filtering>false</filtering>
-                <directory>src/main/resources</directory>
-                <excludes>
-                    <exclude>de/jplag/version.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-
-        <plugins>
-            <plugin>
-                <artifactId>maven-jar-plugin</artifactId>
-                <configuration>
-                    <archive>
-                        <manifest>
-                            <mainClass>de.jplag.CLI</mainClass>
-                            <packageName>jplag</packageName>
-                        </manifest>
-                    </archive>
-                </configuration>
-            </plugin>
-
-            <plugin>
-                <artifactId>maven-assembly-plugin</artifactId>
-                <configuration>
-                    <descriptorRefs>
-                        <descriptorRef>jar-with-dependencies</descriptorRef>
-                    </descriptorRefs>
-                    <archive>
-                        <manifest>
-                            <mainClass>de.jplag.CLI</mainClass>
-                            <packageName>jplag</packageName>
-                        </manifest>
-                    </archive>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>de.jplag</groupId>
+        <artifactId>aggregator</artifactId>
+        <version>3.1.0-SNAPSHOT</version>
+    </parent>
+    <artifactId>jplag</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>net.sourceforge.argparse4j</groupId>
+            <artifactId>argparse4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.github.stefanbirkner</groupId>
+            <artifactId>system-rules</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-math3</artifactId>
+            <version>3.6.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <version>4.0.0</version>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>frontend-utils</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>text</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>java</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>python-3</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>csharp-1.2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>cpp</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>scheme</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>de.jplag</groupId>
+            <artifactId>chars</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <resources>
+            <resource>
+                <filtering>true</filtering>
+                <directory>src/main/resources</directory>
+            </resource>
+
+            <resource>
+                <filtering>false</filtering>
+                <directory>src/main/resources</directory>
+                <excludes>
+                    <exclude>de/jplag/version.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+                <configuration>
+                    <archive>
+                        <manifest>
+                            <mainClass>de.jplag.CLI</mainClass>
+                            <packageName>jplag</packageName>
+                        </manifest>
+                    </archive>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <artifactId>maven-assembly-plugin</artifactId>
+                <configuration>
+                    <descriptorRefs>
+                        <descriptorRef>jar-with-dependencies</descriptorRef>
+                    </descriptorRefs>
+                    <archive>
+                        <manifest>
+                            <mainClass>de.jplag.CLI</mainClass>
+                            <packageName>jplag</packageName>
+                        </manifest>
+                    </archive>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

+ 4 - 2
jplag/src/main/java/de/jplag/CLI.java

@@ -121,9 +121,11 @@ public class CLI {
         Optional.ofNullable((Float) CLUSTER_SPECTRAL_NOISE.getFrom(namespace)).ifPresent(clusteringBuilder::spectralGPVariance);
         Optional.ofNullable((Integer) CLUSTER_SPECTRAL_MIN_RUNS.getFrom(namespace)).ifPresent(clusteringBuilder::spectralMinRuns);
         Optional.ofNullable((Integer) CLUSTER_SPECTRAL_MAX_RUNS.getFrom(namespace)).ifPresent(clusteringBuilder::spectralMaxRuns);
-        Optional.ofNullable((Integer) CLUSTER_SPECTRAL_KMEANS_ITERATIONS.getFrom(namespace)).ifPresent(clusteringBuilder::spectralMaxKMeansIterationPerRun);
+        Optional.ofNullable((Integer) CLUSTER_SPECTRAL_KMEANS_ITERATIONS.getFrom(namespace))
+                .ifPresent(clusteringBuilder::spectralMaxKMeansIterationPerRun);
         Optional.ofNullable((Float) CLUSTER_AGGLOMERATIVE_THRESHOLD.getFrom(namespace)).ifPresent(clusteringBuilder::agglomerativeThreshold);
-        Optional.ofNullable((AgglomerativeClustering.InterClusterSimilarity) CLUSTER_AGGLOMERATIVE_INTER_CLUSTER_SIMILARITY.getFrom(namespace)).ifPresent(clusteringBuilder::agglomerativeInterClusterSimilarity);
+        Optional.ofNullable((AgglomerativeClustering.InterClusterSimilarity) CLUSTER_AGGLOMERATIVE_INTER_CLUSTER_SIMILARITY.getFrom(namespace))
+                .ifPresent(clusteringBuilder::agglomerativeInterClusterSimilarity);
         Optional.ofNullable((Boolean) CLUSTER_PREPROCESSING_NONE.getFrom(namespace)).ifPresent(none -> {
             if (none) {
                 clusteringBuilder.preprocessor(Preprocessors.NONE);

+ 2 - 3
jplag/src/main/java/de/jplag/CliGroupHelper.java

@@ -3,10 +3,10 @@ package de.jplag;
 import java.util.HashMap;
 import java.util.Map;
 
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
 import net.sourceforge.argparse4j.inf.ArgumentContainer;
 import net.sourceforge.argparse4j.inf.ArgumentGroup;
+import net.sourceforge.argparse4j.inf.ArgumentParser;
+import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
 
 public class CliGroupHelper {
 
@@ -26,5 +26,4 @@ public class CliGroupHelper {
         return argumentGroups.computeIfAbsent(name, parser::addArgumentGroup);
     }
 
-
 }

+ 49 - 28
jplag/src/main/java/de/jplag/CommandLineArgument.java

@@ -1,22 +1,16 @@
 package de.jplag;
 
+import static de.jplag.CLI.CLUSTERING_GROUP_NAME;
+import static de.jplag.CLI.CLUSTERING_PREPROCESSING_GROUP_NAME;
 import static de.jplag.options.JPlagOptions.DEFAULT_COMPARISON_MODE;
 import static de.jplag.options.JPlagOptions.DEFAULT_SHOWN_COMPARISONS;
 import static de.jplag.options.JPlagOptions.DEFAULT_SIMILARITY_THRESHOLD;
-import static de.jplag.CLI.CLUSTERING_GROUP_NAME;
-import static de.jplag.CLI.CLUSTERING_PREPROCESSING_GROUP_NAME;
 import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;
 
 import java.util.Collection;
 import java.util.List;
 import java.util.Optional;
 
-import de.jplag.clustering.Algorithms;
-import de.jplag.clustering.ClusteringOptions;
-import de.jplag.clustering.algorithm.AgglomerativeClustering;
-import de.jplag.options.LanguageOption;
-import de.jplag.options.SimilarityMetric;
-import de.jplag.strategy.ComparisonMode;
 import net.sourceforge.argparse4j.impl.Arguments;
 import net.sourceforge.argparse4j.inf.Argument;
 import net.sourceforge.argparse4j.inf.ArgumentAction;
@@ -24,6 +18,13 @@ import net.sourceforge.argparse4j.inf.ArgumentContainer;
 import net.sourceforge.argparse4j.inf.ArgumentParser;
 import net.sourceforge.argparse4j.inf.Namespace;
 
+import de.jplag.clustering.Algorithms;
+import de.jplag.clustering.ClusteringOptions;
+import de.jplag.clustering.algorithm.AgglomerativeClustering;
+import de.jplag.options.LanguageOption;
+import de.jplag.options.SimilarityMetric;
+import de.jplag.strategy.ComparisonMode;
+
 /**
  * Command line arguments for the JPlag CLI. Each argument is defined through an enumeral.
  * @author Timur Saglam
@@ -33,7 +34,8 @@ public enum CommandLineArgument {
     ROOT_DIRECTORY(new Builder("rootDir", String.class).nargs(NumberOfArgumentValues.ONE_OR_MORE_VALUES)),
     LANGUAGE(new Builder("-l", String.class).defaultsTo(LanguageOption.getDefault().getDisplayName()).choices(LanguageOption.getAllDisplayNames())),
     BASE_CODE("-bc", String.class),
-    VERBOSITY(new Builder("-v", String.class).defaultsTo("quiet").choices(List.of("quiet", "long"))), // TODO SH: Replace verbosity when integrating a real logging library
+    VERBOSITY(new Builder("-v", String.class).defaultsTo("quiet").choices(List.of("quiet", "long"))), // TODO SH: Replace verbosity when integrating a
+                                                                                                      // real logging library
     DEBUG("-d", Boolean.class),
     SUBDIRECTORY("-S", String.class),
     SUFFIXES("-p", String.class),
@@ -44,21 +46,42 @@ public enum CommandLineArgument {
     RESULT_FOLDER(new Builder("-r", String.class).defaultsTo("result")),
     COMPARISON_MODE(new Builder("-c", String.class).defaultsTo(DEFAULT_COMPARISON_MODE.getName()).choices(ComparisonMode.allNames())),
     CLUSTER_ENABLE(new Builder("--cluster-skip", Boolean.class).argumentGroup(CLUSTERING_GROUP_NAME).action(Arguments.storeTrue())),
-    CLUSTER_ALGORITHM(new Builder("--cluster-alg", Algorithms.class).argumentGroup(CLUSTERING_GROUP_NAME).defaultsTo(ClusteringOptions.DEFAULTS.getAlgorithm())),
-    CLUSTER_METRIC(new Builder("--cluster-metric", SimilarityMetric.class).argumentGroup(CLUSTERING_GROUP_NAME).defaultsTo(ClusteringOptions.DEFAULTS.getSimilarityMetric())),
-    CLUSTER_SPECTRAL_BANDWIDTH(new Builder("--cluster-spectral-bandwidth", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("bandwidth").defaultsTo(ClusteringOptions.DEFAULTS.getSpectralKernelBandwidth())),
-    CLUSTER_SPECTRAL_NOISE(new Builder("--cluster-spectral-noise", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("noise").defaultsTo(ClusteringOptions.DEFAULTS.getSpectralGPVariance())),
-    CLUSTER_SPECTRAL_MIN_RUNS(new Builder("--cluster-spectral-min-runs", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("min").defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMinRuns())),
-    CLUSTER_SPECTRAL_MAX_RUNS(new Builder("--cluster-spectral-max-runs", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("max").defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMaxRuns())),
-    CLUSTER_SPECTRAL_KMEANS_ITERATIONS(new Builder("--cluster-spectral-kmeans-interations", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("iterations").defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMaxKMeansIterationPerRun())),
-    CLUSTER_AGGLOMERATIVE_THRESHOLD(new Builder("--cluster-agglomerative-threshold", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("threshold").defaultsTo(ClusteringOptions.DEFAULTS.getAgglomerativeThreshold())),
-    CLUSTER_AGGLOMERATIVE_INTER_CLUSTER_SIMILARITY(new Builder("--cluster-agglomerative-inter-cluster-similarity", AgglomerativeClustering.InterClusterSimilarity.class).argumentGroup(CLUSTERING_GROUP_NAME).defaultsTo(ClusteringOptions.DEFAULTS.getAgglomerativeInterClusterSimilarity())),
-    CLUSTER_PREPROCESSING_NONE(new Builder("--cluster-pp-none", Boolean.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).action(Arguments.storeTrue())),
-    CLUSTER_PREPROCESSING_CDF(new Builder("--cluster-pp-cdf", Boolean.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).action(Arguments.storeTrue())),
-    CLUSTER_PREPROCESSING_PERCENTILE(new Builder("--cluster-pp-percentile", Float.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).metaVar("percentile")),
-    CLUSTER_PREPROCESSING_THRESHOLD(new Builder("--cluster-pp-threshold", Float.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).metaVar("threshold"));
-
-
+    CLUSTER_ALGORITHM(
+            new Builder("--cluster-alg", Algorithms.class).argumentGroup(CLUSTERING_GROUP_NAME)
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getAlgorithm())),
+    CLUSTER_METRIC(
+            new Builder("--cluster-metric", SimilarityMetric.class).argumentGroup(CLUSTERING_GROUP_NAME)
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSimilarityMetric())),
+    CLUSTER_SPECTRAL_BANDWIDTH(
+            new Builder("--cluster-spectral-bandwidth", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("bandwidth")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSpectralKernelBandwidth())),
+    CLUSTER_SPECTRAL_NOISE(
+            new Builder("--cluster-spectral-noise", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("noise")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSpectralGPVariance())),
+    CLUSTER_SPECTRAL_MIN_RUNS(
+            new Builder("--cluster-spectral-min-runs", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("min")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMinRuns())),
+    CLUSTER_SPECTRAL_MAX_RUNS(
+            new Builder("--cluster-spectral-max-runs", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("max")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMaxRuns())),
+    CLUSTER_SPECTRAL_KMEANS_ITERATIONS(
+            new Builder("--cluster-spectral-kmeans-interations", Integer.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("iterations")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getSpectralMaxKMeansIterationPerRun())),
+    CLUSTER_AGGLOMERATIVE_THRESHOLD(
+            new Builder("--cluster-agglomerative-threshold", Float.class).argumentGroup(CLUSTERING_GROUP_NAME).metaVar("threshold")
+                    .defaultsTo(ClusteringOptions.DEFAULTS.getAgglomerativeThreshold())),
+    CLUSTER_AGGLOMERATIVE_INTER_CLUSTER_SIMILARITY(
+            new Builder("--cluster-agglomerative-inter-cluster-similarity", AgglomerativeClustering.InterClusterSimilarity.class)
+                    .argumentGroup(CLUSTERING_GROUP_NAME).defaultsTo(ClusteringOptions.DEFAULTS.getAgglomerativeInterClusterSimilarity())),
+    CLUSTER_PREPROCESSING_NONE(
+            new Builder("--cluster-pp-none", Boolean.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME)
+                    .action(Arguments.storeTrue())),
+    CLUSTER_PREPROCESSING_CDF(
+            new Builder("--cluster-pp-cdf", Boolean.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).action(Arguments.storeTrue())),
+    CLUSTER_PREPROCESSING_PERCENTILE(
+            new Builder("--cluster-pp-percentile", Float.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).metaVar("percentile")),
+    CLUSTER_PREPROCESSING_THRESHOLD(
+            new Builder("--cluster-pp-threshold", Float.class).mutuallyExclusiveGroup(CLUSTERING_PREPROCESSING_GROUP_NAME).metaVar("threshold"));
 
     private final String flag;
     private final NumberOfArgumentValues numberOfValues;
@@ -132,10 +155,8 @@ public enum CommandLineArgument {
      * @param parser is that parser.
      */
     public void parseWith(ArgumentParser parser, CliGroupHelper groupHelper) {
-        ArgumentContainer argContainer = mutuallyExclusiveGroup
-            .map(groupHelper::getMutuallyExclusiveGroup)
-            .or(() -> argumentGroup.map(groupHelper::getArgumentGroup))
-            .orElse(parser);
+        ArgumentContainer argContainer = mutuallyExclusiveGroup.map(groupHelper::getMutuallyExclusiveGroup)
+                .or(() -> argumentGroup.map(groupHelper::getArgumentGroup)).orElse(parser);
 
         Argument argument = argContainer.addArgument(flag).help(description);
         choices.ifPresent(it -> argument.choices(it));

+ 1 - 1
jplag/src/main/java/de/jplag/JPlag.java

@@ -82,7 +82,7 @@ public class JPlag {
         if (submissionSet.hasBaseCode()) {
             coreAlgorithm.createHashes(submissionSet.getBaseCode().getTokenList(), options.getMinimumTokenMatch(), true);
         }
-        
+
         int submissionCount = submissionSet.numberOfSubmissions();
         if (submissionCount < 2) {
             throw new SubmissionException("Not enough valid submissions! (found " + submissionCount + " valid submissions)");

+ 2 - 1
jplag/src/main/java/de/jplag/clustering/Algorithms.java

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

+ 6 - 6
jplag/src/main/java/de/jplag/clustering/ClusteringAdapter.java

@@ -14,15 +14,15 @@ 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>
+ * <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) {
@@ -56,7 +56,8 @@ public class ClusteringAdapter {
         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);
+                return new ClusteringResult.DefaultCluster<T>(unmappedCluster.getMembers().stream().map(mapping).collect(Collectors.toList()),
+                        unmappedCluster.getCommunityStrength(), this);
             }).collect(Collectors.toList());
             size = unmapped.size();
         }
@@ -76,6 +77,5 @@ public class ClusteringAdapter {
             return size;
         }
 
-    } 
+    }
 }
- 

+ 5 - 6
jplag/src/main/java/de/jplag/clustering/ClusteringFactory.java

@@ -7,9 +7,9 @@ import java.util.stream.Collectors;
 
 import de.jplag.JPlagComparison;
 import de.jplag.Submission;
+import de.jplag.clustering.algorithm.AgglomerativeClustering;
 import de.jplag.clustering.algorithm.ClusteringAlgorithm;
 import de.jplag.clustering.algorithm.SpectralClustering;
-import de.jplag.clustering.algorithm.AgglomerativeClustering;
 import de.jplag.clustering.preprocessors.CdfPreprocessor;
 import de.jplag.clustering.preprocessors.PercentileThresholdProcessor;
 import de.jplag.clustering.preprocessors.ThresholdPreprocessor;
@@ -19,7 +19,8 @@ import de.jplag.clustering.preprocessors.ThresholdPreprocessor;
  */
 public class ClusteringFactory {
     public static List<ClusteringResult<Submission>> getClusterings(Collection<JPlagComparison> comparisons, ClusteringOptions options) {
-        if (!options.isEnabled()) return Collections.emptyList();
+        if (!options.isEnabled())
+            return Collections.emptyList();
 
         // init algorithm
         ClusteringAlgorithm ca = null;
@@ -68,7 +69,7 @@ public class ClusteringFactory {
 
         // remove bad clusters
         result = removeBadClusters(result);
-        
+
         return List.of(result);
     }
 
@@ -77,9 +78,7 @@ public class ClusteringFactory {
 
             @Override
             public Collection<Cluster<Submission>> getClusters() {
-                return clustering.getClusters().stream()
-                    .filter(cluster -> !cluster.isBadCluster())
-                    .collect(Collectors.toList());
+                return clustering.getClusters().stream().filter(cluster -> !cluster.isBadCluster()).collect(Collectors.toList());
             }
 
             @Override

+ 1 - 2
jplag/src/main/java/de/jplag/clustering/ClusteringOptions.java

@@ -157,8 +157,7 @@ public class ClusteringOptions {
             return Builder.this;
         }
 
-        public Builder agglomerativeInterClusterSimilarity(
-                AgglomerativeClustering.InterClusterSimilarity agglomerativeInterClusterSimilarity) {
+        public Builder agglomerativeInterClusterSimilarity(AgglomerativeClustering.InterClusterSimilarity agglomerativeInterClusterSimilarity) {
             this.agglomerativeInterClusterSimilarity = agglomerativeInterClusterSimilarity;
             return Builder.this;
         }

+ 19 - 38
jplag/src/main/java/de/jplag/clustering/ClusteringResult.java

@@ -11,22 +11,11 @@ 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.
+     * 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. 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 It's called modularity in that paper.
      * @return community strength
      */
     float getCommunityStrength();
@@ -34,13 +23,10 @@ public interface ClusteringResult<T> {
     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();
+        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();
 
@@ -53,28 +39,29 @@ public interface ClusteringResult<T> {
         ClusteringResult<T> getClusteringResult();
 
         /**
-         * @return How much each member of this cluster contributes to the {@link ClusteringResult#getCommunityStrength} 
+         * @return How much each member of this cluster contributes to the {@link ClusteringResult#getCommunityStrength}
          */
         default float getCommunityStrengthPerConnection() {
             int size = getMembers().size();
-            if (size < 2) return 0;
+            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.
-         * 
+         * 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());
+            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();
+            if (size < 2)
+                return getCommunityStrengthPerConnection();
             return getCommunityStrengthPerConnection() / posCommunityStrengthSum;
         }
 
@@ -92,7 +79,6 @@ public interface ClusteringResult<T> {
 
         /**
          * Computes the average similarity inside the cluster.
-         * 
          * @param similarity function that supplies the similarity of two cluster members.
          * @return average similarity
          */
@@ -120,7 +106,6 @@ public interface ClusteringResult<T> {
         }
     }
 
-
     public static class DefaultCluster<T> implements Cluster<T> {
 
         private float communityStrength;
@@ -148,9 +133,5 @@ public interface ClusteringResult<T> {
             return clusteringResult;
         }
 
-
-
-    } 
+    }
 }
-
-

+ 6 - 4
jplag/src/main/java/de/jplag/clustering/IntegerClusteringResult.java

@@ -36,10 +36,12 @@ public class IntegerClusteringResult implements ClusteringResult<Integer> {
             RealMatrix E = new Array2DRowRealMatrix(clusters.size(), clusters.size());
             E = E.scalarMultiply(0);
             for (int i = 0; i < N; i++) {
-                if (!submissionIdx2ClusterIdx.containsKey(i)) continue;
+                if (!submissionIdx2ClusterIdx.containsKey(i))
+                    continue;
                 int clusterA = submissionIdx2ClusterIdx.get(i);
                 for (int j = i + 1; j < N; j++) {
-                    if (!submissionIdx2ClusterIdx.containsKey(j)) continue;
+                    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));
@@ -52,7 +54,7 @@ public class IntegerClusteringResult implements ClusteringResult<Integer> {
                 this.clusters.add(new DefaultCluster<Integer>(clusters.get(i), (float) clusterCommunityStrength, this));
                 communityStrength += clusterCommunityStrength;
             }
-        }   
+        }
         size = this.clusters.stream().mapToInt(x -> x.getMembers().size()).sum();
     }
 
@@ -70,5 +72,5 @@ public class IntegerClusteringResult implements ClusteringResult<Integer> {
     public int size() {
         return size;
     }
-    
+
 }

+ 1 - 1
jplag/src/main/java/de/jplag/clustering/IntegerMapping.java

@@ -12,7 +12,7 @@ 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);

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

@@ -14,6 +14,7 @@ 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 {

+ 4 - 1
jplag/src/main/java/de/jplag/clustering/Preprocessors.java

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

+ 19 - 19
jplag/src/main/java/de/jplag/clustering/algorithm/AgglomerativeClustering.java

@@ -43,7 +43,8 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
                 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)));
+                    initialSimilarities
+                            .add(new ClusterConnection(leftCluster, rightCluster, (float) similarityMatrix.getEntry(leftIndex, rightIndex)));
                 }
             }
 
@@ -75,14 +76,14 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
         float similarity = 0;
         switch (options.similarity) {
             case MIN:
-            similarity = Float.MAX_VALUE;
-            break;
+                similarity = Float.MAX_VALUE;
+                break;
             case MAX:
-            similarity = -Float.MAX_VALUE;
-            break;
+                similarity = -Float.MAX_VALUE;
+                break;
             case AVERAGE:
-            similarity = 0;
-            break;
+                similarity = 0;
+                break;
         }
 
         for (int leftIndex = 0; leftIndex < leftCluster.size(); leftIndex++) {
@@ -91,18 +92,17 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
                 float submissionSimilarity = (float) similarityMatrix.getEntry(leftSubmission, rightCluster.get(rightIndex));
                 switch (options.similarity) {
                     case MIN:
-                    similarity = Math.min(similarity, submissionSimilarity);
-                    break;
+                        similarity = Math.min(similarity, submissionSimilarity);
+                        break;
                     case MAX:
-                    similarity = Math.max(similarity, submissionSimilarity);
-                    break;
+                        similarity = Math.max(similarity, submissionSimilarity);
+                        break;
                     case AVERAGE:
-                    similarity += submissionSimilarity;
+                        similarity += submissionSimilarity;
                 }
             }
         }
-    
-        
+
         if (options.similarity == InterClusterSimilarity.AVERAGE) {
             similarity /= leftCluster.size() * rightCluster.size();
         }
@@ -111,7 +111,7 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
 
     public static class ClusteringOptions {
         public float minimalSimilarity = 0.1f;
-        public InterClusterSimilarity similarity = InterClusterSimilarity.AVERAGE; 
+        public InterClusterSimilarity similarity = InterClusterSimilarity.AVERAGE;
     }
 
     public static enum InterClusterSimilarity {
@@ -140,7 +140,7 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
         public int compareTo(ClusterConnection other) {
             return (int) Math.signum(other.similarity - similarity);
         }
-        
+
     }
 
     private class Cluster {
@@ -153,7 +153,7 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
         public List<Integer> getSubmissions() {
             return submissions;
         }
-        
+
     }
 
     private class MergedList extends AbstractList<Integer> {
@@ -180,7 +180,7 @@ public class AgglomerativeClustering implements ClusteringAlgorithm {
         public int size() {
             return size;
         }
-        
+
     }
-    
+
 }

+ 155 - 202
jplag/src/main/java/de/jplag/clustering/algorithm/BFGS.java

@@ -1,29 +1,24 @@
 /**
- * The original version of this file originates from SMILE:
- * https://github.com/haifengl/smile
+ * 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/>.
+ * 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 static java.lang.Math.abs;
+import static java.lang.Math.max;
+import static java.lang.Math.min;
+import static java.lang.Math.sqrt;
+
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;
 import java.util.stream.Collectors;
@@ -37,60 +32,43 @@ 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.
+ * 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.
+ * 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.
+ * 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.
- *
+ * 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>
+ * <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);
+    // 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. */
@@ -99,57 +77,45 @@ public class BFGS {
     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.
+     * 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
+     * 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>.
+     * 
+     * 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
+     * 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.
-     *
+     * 
+     * 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 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.
-     *
+     * @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) {
@@ -181,7 +147,8 @@ public class BFGS {
         }
 
         if (slope >= 0) {
-            //throw new IllegalArgumentException("Line Search: the search direction is not a descent direction, which may be caused by roundoff problem.");
+            // throw new IllegalArgumentException("Line Search: the search direction is not a descent direction, which may be caused
+            // by roundoff problem.");
         }
 
         // Calculate minimum step.
@@ -252,34 +219,22 @@ public class BFGS {
     }
 
     /**
-     * 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.
-     *
+     * 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 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) {
@@ -318,7 +273,7 @@ public class BFGS {
         double[] p = new double[n];
         double[] g = new double[n];
         double[] cauchy = new double[n];
-        double f   = func.g(x, g);
+        double f = func.g(x, g);
 
         double[] x_old = new double[n];
         double[] g_old = new double[n];
@@ -327,7 +282,7 @@ public class BFGS {
         double stpmax = STPMX * max(norm(x), n);
 
         for (int iter = 1; iter <= maxIter; iter++) {
-            double f_old   = f;
+            double f_old = f;
             System.arraycopy(x, 0, x_old, 0, n);
             System.arraycopy(g, 0, g_old, 0, n);
 
@@ -349,7 +304,7 @@ public class BFGS {
 
             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");
+                    // 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;
                 }
@@ -358,18 +313,18 @@ public class BFGS {
             // 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");
+                // 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));
+                // 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));
+                // logger.info(String.format("L-BFGS-B: the function value after %3d iterations: %.5f", iter, f));
             }
 
             // prepare for next iteration
@@ -384,8 +339,8 @@ public class BFGS {
             double test = abs(sy);
             if (test > EPSILON * yy) {
                 if (yHistory.size() >= m) {
-                    yHistory.remove (0);
-                    sHistory.remove (0);
+                    yHistory.remove(0);
+                    sHistory.remove(0);
                 }
 
                 yHistory.add(y);
@@ -395,8 +350,8 @@ public class BFGS {
                 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);
+                    W = new Matrix(n, 2 * h);
+                    M = new Matrix(2 * h, 2 * h);
                 }
 
                 // STEP 7
@@ -409,7 +364,7 @@ public class BFGS {
                         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);
+                        W.set(i, h + j, sj[i] * theta);
                     }
                 }
 
@@ -418,33 +373,34 @@ public class BFGS {
                 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);
+                        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 = 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.set(h + i, h + j, theta * SS.get(i, j));
                     }
                 }
 
-                //M.uplo(UPLO.LOWER);
+                // 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);
+            // 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));
+                // 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));
+        // logger.warn(String.format("L-BFGS-B reaches maximum %d iterations: %.5f", maxIter, f));
         return f;
     }
 
@@ -465,8 +421,8 @@ public class BFGS {
 
     /**
      * Algorithm CP: Computation of the Generalized Cauchy Point. See page 8.
-     * @param x  the parameter vector
-     * @param g  the gradient vector
+     * @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;
@@ -474,24 +430,24 @@ public class BFGS {
         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];
+            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;
+        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;
+            if (t[index[i]] >= 0)
+                break;
         }
 
         double dt = i < n ? t[i] : 0;
@@ -500,25 +456,24 @@ public class BFGS {
             double tb = t[i];
             dt = tb - t_old;
 
-            cauchy[b] = d[b] > 0 ? u[b] :
-                       (d[b] < 0 ? l[b] : cauchy[b]);
+            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));
+            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);
+            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;
+            d[b] = 0;
+            dt_min = -fPrime / fDoublePrime;
+            t_old = tb;
         }
 
         dt_min = max(dt_min, 0.0);
@@ -538,13 +493,13 @@ public class BFGS {
 
     /**
      * 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
+     * @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) {
+    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<>();
@@ -572,7 +527,7 @@ public class BFGS {
         }
 
         Matrix WZ = W.row(freeVar);
-        double[] v  = M.mv(WZ.tv(r));
+        double[] v = M.mv(WZ.tv(r));
         Matrix N = WZ.ata().mul(-thetaInverse);
         N = M.mm(N);
         int n1 = N.nrows();
@@ -590,7 +545,7 @@ public class BFGS {
             du[i] = -thetaInverse * (r[i] + wzv[i] * thetaInverse);
         }
         double alphaStar = findAlpha(cauchy, du, l, u, freeVar);
-        double[] dStar   = new double[freeVarCount];
+        double[] dStar = new double[freeVarCount];
         for (int i = 0; i < freeVarCount; i++) {
             dStar[i] = du[i] * alphaStar;
         }
@@ -605,9 +560,9 @@ public class BFGS {
 
     /**
      * 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
+     * @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;
@@ -615,17 +570,16 @@ public class BFGS {
 
         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]);
+            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
+     * 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;
@@ -633,8 +587,10 @@ public class BFGS {
 
         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);
+            if (gi < 0)
+                gi = max(x[i] - u[i], gi);
+            else
+                gi = min(x[i] - l[i], gi);
             norm = max(norm, abs(gi));
         }
 
@@ -643,14 +599,16 @@ public class BFGS {
 
     /**
      * Clamps the values of v to stay within the pre-defined bounds.
-     * @param v  the vector to be adjusted
+     * @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];
+            if (v[i] > u[i])
+                v[i] = u[i];
+            else if (v[i] < l[i])
+                v[i] = l[i];
         }
     }
 
@@ -666,19 +624,17 @@ public class BFGS {
     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.
-         *
+         * 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++) {
@@ -690,21 +646,19 @@ public class BFGS {
                 }
                 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))
-            .collect(Collectors.toList());
+        List<Pair<Integer, Double>> sortedPairs = IntStream.range(0, array.length).mapToObj(idx -> Pair.create(idx, array[idx]))
+                .sorted(Comparator.comparingDouble(Pair::getValue)).collect(Collectors.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);
@@ -772,10 +726,10 @@ public class BFGS {
         public Matrix ata() {
             Matrix C = new Matrix(d.transpose().multiply(d));
             // C.mm(TRANSPOSE, 1this, NO_TRANSPOSE, this);
-            //C.uplo(LOWER);
+            // C.uplo(LOWER);
             return C;
         }
-        
+
         /**
          * Returns {@code A[i,j]}.
          * @param i the row index.
@@ -804,9 +758,8 @@ public class BFGS {
         }
 
         /**
-         * 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.
+         * 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.
          */
@@ -843,10 +796,10 @@ public class BFGS {
         }
 
         /**
-        * 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.
-        */
+         * 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];
 
@@ -877,6 +830,6 @@ public class BFGS {
         public DecompositionSolver lu() {
             return new LUDecomposition(d).getSolver();
         }
-        
+
     }
 }

+ 10 - 15
jplag/src/main/java/de/jplag/clustering/algorithm/BayesianOptimization.java

@@ -28,9 +28,8 @@ public class BayesianOptimization {
     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
@@ -56,10 +55,7 @@ public class BayesianOptimization {
     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));
+        return Stream.generate(g::nextVector).map(x -> new ArrayRealVector(x)).map(x -> x.ebeMultiply(size)).map(x -> x.add(minima));
 
     }
 
@@ -96,19 +92,20 @@ public class BayesianOptimization {
         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;
+            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++) {
+            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) {
+            }
+            if (poi > bestScore) {
                 bestSolution = r;
                 bestScore = poi;
             }
@@ -127,9 +124,7 @@ public class BayesianOptimization {
         OptimizationResult<T> best = null;
 
         // the first couple of executions are reserved for exploration
-        sampleSolutionSpace()
-            .limit(initialPoints)
-            .forEach(X::add);
+        sampleSolutionSpace().limit(initialPoints).forEach(X::add);
 
         Spliterator<RealVector> poiSampler = sampleSolutionSpace().spliterator();
         double[] zeroAcquisitionsCounter = new double[1];
@@ -184,5 +179,5 @@ public class BayesianOptimization {
         public RealVector getParams() {
             return params;
         }
-    } 
+    }
 }

+ 24 - 18
jplag/src/main/java/de/jplag/clustering/algorithm/GaussianProcess.java

@@ -24,7 +24,8 @@ public class GaussianProcess {
     private CholeskyDecomposition cholesky;
     private RealVector lengthScale;
 
-    private GaussianProcess(List<RealVector> X, RealVector weight, double mean, double standardDeviation, CholeskyDecomposition cholesky, 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;
@@ -33,7 +34,7 @@ public class GaussianProcess {
         this.lengthScale = lengthScale;
     }
 
-     /**
+    /**
      * @param x position to predict at
      * @return mean prediction at x
      */
@@ -70,9 +71,9 @@ public class GaussianProcess {
     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 
+     * 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
@@ -80,29 +81,31 @@ public class GaussianProcess {
     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 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.
+     * @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();
+        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()));
+            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()));
+            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;
@@ -121,12 +124,12 @@ public class GaussianProcess {
 
         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) 
+     * 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());
@@ -186,9 +189,12 @@ public class GaussianProcess {
         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] = '+';
+            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();
@@ -196,7 +202,7 @@ public class GaussianProcess {
             sb.append(out[i]);
             if (i < 98) {
                 sb.append('\n');
-            } 
+            }
         }
         return sb.toString();
     }

+ 35 - 31
jplag/src/main/java/de/jplag/clustering/algorithm/SpectralClustering.java

@@ -32,7 +32,8 @@ public class SpectralClustering implements ClusteringAlgorithm {
 
     @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
+        // 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
@@ -40,7 +41,8 @@ public class SpectralClustering implements ClusteringAlgorithm {
         W.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
             @Override
             public double visit(int row, int column, double value) {
-                if (row == column) return 0;
+                if (row == column)
+                    return 0;
                 return similarityMatrix.getEntry(row, column);
             }
         });
@@ -49,7 +51,8 @@ public class SpectralClustering implements ClusteringAlgorithm {
         D_pow_minus_1_over_2.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
             @Override
             public double visit(int row, int column, double value) {
-                if (row != column) return 0;
+                if (row != column)
+                    return 0;
                 return 1 / Math.sqrt(W.getRowVector(row).getL1Norm());
             }
         });
@@ -64,7 +67,6 @@ public class SpectralClustering implements ClusteringAlgorithm {
         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);
@@ -75,18 +77,20 @@ public class SpectralClustering implements ClusteringAlgorithm {
         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 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 new BayesianOptimization.OptimizationResult<>(modularityRes.getWorth((a, b) -> (float) similarityMatrix.getEntry(a, b)),
+                    clustering);
         });
 
         return boResult.getValue();
@@ -95,17 +99,18 @@ public class SpectralClustering implements ClusteringAlgorithm {
     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);
-           }; 
+            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());
-        
+        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);   
+        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());
@@ -128,36 +133,35 @@ public class SpectralClustering implements ClusteringAlgorithm {
 
     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.
+         * 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.
+         * 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. 
+         * 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.
+         * 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;
 
     }
-    
+
 }

+ 5 - 6
jplag/src/main/java/de/jplag/clustering/preprocessors/CdfPreprocessor.java

@@ -11,17 +11,16 @@ 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
+ * 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{
+public class CdfPreprocessor implements Preprocessor {
 
     private PreprocessorHelper helper = new PreprocessorHelper();
 
     @Override
     public double[][] preprocessSimilarities(double[][] similarityMatrix) {
-        RealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, true); 
+        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];
@@ -51,5 +50,5 @@ public class CdfPreprocessor implements Preprocessor{
     public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
         return helper.postProcessResult(result);
     }
-    
+
 }

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

@@ -11,7 +11,7 @@ import de.jplag.clustering.Preprocessor;
 
 public class PercentileThresholdProcessor implements Preprocessor {
 
-    private float percentile; 
+    private float percentile;
     private ThresholdPreprocessor tp;
 
     public PercentileThresholdProcessor(float percentile) {
@@ -20,7 +20,7 @@ public class PercentileThresholdProcessor implements Preprocessor {
 
     @Override
     public double[][] preprocessSimilarities(double[][] similarityMatrix) {
-        Array2DRowRealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, false); 
+        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];
@@ -46,5 +46,5 @@ public class PercentileThresholdProcessor implements Preprocessor {
     public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
         return tp.postProcessResult(result);
     }
-    
+
 }

+ 1 - 2
jplag/src/main/java/de/jplag/clustering/preprocessors/ThresholdPreprocessor.java

@@ -33,6 +33,5 @@ public class ThresholdPreprocessor implements Preprocessor {
     public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
         return helper.postProcessResult(result);
     }
-    
-    
+
 }

+ 1 - 1
jplag/src/main/java/de/jplag/options/JPlagOptions.java

@@ -255,7 +255,7 @@ public class JPlagOptions {
             this.maximumNumberOfComparisons = maximumNumberOfComparisons;
         }
     }
-    
+
     public void setMinimumTokenMatch(Integer minimumTokenMatch) {
         if (minimumTokenMatch != null && minimumTokenMatch < 1) {
             this.minimumTokenMatch = 1;

+ 1 - 1
jplag/src/test/java/de/jplag/cli/ClusteringTest.java

@@ -8,7 +8,7 @@ import de.jplag.CommandLineArgument;
 import de.jplag.clustering.Preprocessors;
 
 public class ClusteringTest extends CommandLineInterfaceTest {
-    
+
     @Test
     public void parsePercentilePreProcessor() {
         String argument = CommandLineArgument.CLUSTER_PREPROCESSING_PERCENTILE.flag() + "=" + Float.toString(0.5f);

+ 27 - 21
jplag/src/test/java/de/jplag/clustering/ClusteringTest.java

@@ -34,7 +34,7 @@ import de.jplag.clustering.algorithm.SpectralClustering;
 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());
@@ -90,25 +90,26 @@ public class ClusteringTest {
         RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(preprocessor.preprocessSimilarities(r.similarity.getData()));
 
         /*
-        AgglomerativeClustering.ClusteringOptions options = new AgglomerativeClustering.ClusteringOptions();
-        options.minimalSimilarity = 0.15f;
-        options.similarity = AgglomerativeClustering.InterClusterSimilarity.AVERAGE;
-        ClusteringAlgorithm clusteringAlg = new AgglomerativeClustering(options);
-        */
-        
+         * AgglomerativeClustering.ClusteringOptions options = new AgglomerativeClustering.ClusteringOptions();
+         * options.minimalSimilarity = 0.15f; options.similarity = AgglomerativeClustering.InterClusterSimilarity.AVERAGE;
+         * ClusteringAlgorithm clusteringAlg = new AgglomerativeClustering(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))));
+        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(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());
@@ -123,26 +124,28 @@ public class ClusteringTest {
         RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(new CdfPreprocessor().preprocessSimilarities(r.similarity.getData()));
 
         /*
-        AgglomerativeClustering.ClusteringOptions options = new AgglomerativeClustering.ClusteringOptions();
-        options.minimalSimilarity = 0.3f;
-        options.similarity = AgglomerativeClustering.InterClusterSimilarity.AVERAGE;
-        ClusteringAlgorithm clusteringAlg = new AgglomerativeClustering(options);
-        */
-        
+         * AgglomerativeClustering.ClusteringOptions options = new AgglomerativeClustering.ClusteringOptions();
+         * options.minimalSimilarity = 0.3f; options.similarity = AgglomerativeClustering.InterClusterSimilarity.AVERAGE;
+         * ClusteringAlgorithm clusteringAlg = new AgglomerativeClustering(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))));
+        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;
+            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(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());
@@ -179,7 +182,8 @@ public class ClusteringTest {
         try (CSVReader reader = new CSVReader(fileName, ";")) {
             while (reader.hasNext()) {
                 List<String> records = reader.next();
-                if (records.isEmpty()) continue;
+                if (records.isEmpty())
+                    continue;
                 String leftStudent = records.get(1);
                 String rightStudent = records.get(2);
                 String similarity = records.get(3);
@@ -207,7 +211,8 @@ public class ClusteringTest {
         try (CSVReader reader = new CSVReader(fileName, ";")) {
             while (reader.hasNext()) {
                 List<String> records = reader.next();
-                if (records.isEmpty()) continue;
+                if (records.isEmpty())
+                    continue;
                 Deque<String> stuff = new ArrayDeque<>(records);
                 String leftStudent = stuff.removeFirst();
                 int leftID = mapping.map(leftStudent);
@@ -237,6 +242,7 @@ public class ClusteringTest {
     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);

+ 3 - 3
jplag/src/test/java/de/jplag/clustering/algorithm/AgglomerativeClusteringTest.java

@@ -1,7 +1,5 @@
 package de.jplag.clustering.algorithm;
 
-import de.jplag.clustering.algorithm.AgglomerativeClustering.ClusteringOptions;
-
 import static org.junit.Assert.assertTrue;
 
 import java.util.ArrayList;
@@ -12,6 +10,8 @@ import org.apache.commons.math3.linear.RealMatrix;
 import org.junit.Before;
 import org.junit.Test;
 
+import de.jplag.clustering.algorithm.AgglomerativeClustering.ClusteringOptions;
+
 public class AgglomerativeClusteringTest {
     AgglomerativeClustering clustering;
 
@@ -47,7 +47,7 @@ public class AgglomerativeClusteringTest {
             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; 
+            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);
 
     }

+ 4 - 4
jplag/src/test/java/de/jplag/clustering/algorithm/BayesianOptimizationTest.java

@@ -10,14 +10,14 @@ public class BayesianOptimizationTest {
 
     @Test
     public void findParabolaMax() {
-        RealVector minima = new ArrayRealVector(new double[] { -20 });
-        RealVector maxima = new ArrayRealVector(new double[] {  10 });
-        RealVector lengthScale = new ArrayRealVector(new double[] { 5 });
+        RealVector minima = new ArrayRealVector(new double[] {-20});
+        RealVector maxima = new ArrayRealVector(new double[] {10});
+        RealVector lengthScale = new ArrayRealVector(new double[] {5});
         double maximumAt = 1;
         BayesianOptimization bo = new BayesianOptimization(minima, maxima, 3, 15, 1.0 / 12.0, lengthScale);
         double maximumPoint = bo.maximize(v -> {
             double val = v.getEntry(0);
-            double result =  -(val - maximumAt) * (val - maximumAt);
+            double result = -(val - maximumAt) * (val - maximumAt);
             result += 0.2 * (Math.random() - 0.5);
             return new BayesianOptimization.OptimizationResult<Double>(result, result);
         }).getParams().getEntry(0);

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

@@ -10,7 +10,7 @@ import org.apache.commons.math3.linear.RealVector;
 import org.junit.Test;
 
 public class GaussianProcessTest {
-    
+
     @Test
     public void noisyLinearFunction() {
         List<RealVector> X = new ArrayList<>();