ソースを参照

Add clustering options to CLI

Simon Ding 4 年 前
親
コミット
c26a26fe6e

+ 43 - 1
jplag/src/main/java/de/jplag/CLI.java

@@ -13,13 +13,20 @@ import static de.jplag.CommandLineArgument.SHOWN_COMPARISONS;
 import static de.jplag.CommandLineArgument.SUBDIRECTORY;
 import static de.jplag.CommandLineArgument.SUFFIXES;
 import static de.jplag.CommandLineArgument.VERBOSITY;
+import static de.jplag.CommandLineArgument.*;
 
 import java.io.File;
+import java.util.Optional;
 import java.util.Random;
 
+import de.jplag.clustering.Algorithms;
+import de.jplag.clustering.ClusteringOptions;
+import de.jplag.clustering.Preprocessors;
+import de.jplag.clustering.algorithm.TopDownHierarchicalClustering;
 import de.jplag.exceptions.ExitException;
 import de.jplag.options.JPlagOptions;
 import de.jplag.options.LanguageOption;
+import de.jplag.options.SimilarityMetric;
 import de.jplag.options.Verbosity;
 import de.jplag.reporting.Report;
 import de.jplag.strategy.ComparisonMode;
@@ -41,6 +48,8 @@ public class CLI {
             "More Abstract than Tree", "Students Nightmare", "No, changing variable names does not work", "The tech is out there!"};
 
     private static final String PROGRAM_NAME = "jplag";
+    static final String CLUSTERING_GROUP_NAME = "Clustering";
+    static final String CLUSTERING_PREPROCESSING_GROUP_NAME = "Clustering - Preprocessing";
 
     private final ArgumentParser parser;
 
@@ -70,8 +79,9 @@ public class CLI {
      */
     public CLI() {
         parser = ArgumentParsers.newFor(PROGRAM_NAME).build().defaultHelp(true).description(generateDescription());
+        CliGroupHelper groupHelper = new CliGroupHelper(parser);
         for (CommandLineArgument argument : CommandLineArgument.values()) {
-            argument.parseWith(parser);
+            argument.parseWith(parser, groupHelper);
         }
     }
 
@@ -114,6 +124,38 @@ public class CLI {
         options.setMaximumNumberOfComparisons(SHOWN_COMPARISONS.getFrom(namespace));
         ComparisonMode.fromName(COMPARISON_MODE.getFrom(namespace)).ifPresentOrElse(it -> options.setComparisonMode(it),
                 () -> System.out.println("Unknown comparison mode, using default mode!"));
+
+        ClusteringOptions.Builder clusteringBuilder = new ClusteringOptions.Builder();
+        Optional.ofNullable((Boolean) CLUSTER_ENABLE.getFrom(namespace)).ifPresent(clusteringBuilder::enabled);
+        Optional.ofNullable((Algorithms) CLUSTER_ALGORITHM.getFrom(namespace)).ifPresent(clusteringBuilder::algorithm);
+        Optional.ofNullable((SimilarityMetric) CLUSTER_METRIC.getFrom(namespace)).ifPresent(clusteringBuilder::similarityMetric);
+        Optional.ofNullable((Float) CLUSTER_SPECTRAL_BANDWIDTH.getFrom(namespace)).ifPresent(clusteringBuilder::spectralKernelBandwidth);
+        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((Float) CLUSTER_AGGLOMERATIVE_THRESHOLD.getFrom(namespace)).ifPresent(clusteringBuilder::agglomerativeThreshold);
+        Optional.ofNullable((TopDownHierarchicalClustering.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);
+            }
+        });
+        Optional.ofNullable((Boolean) CLUSTER_PREPROCESSING_CDF.getFrom(namespace)).ifPresent(cdf -> {
+            if (cdf) {
+                clusteringBuilder.preprocessor(Preprocessors.CDF);
+            }
+        });
+        Optional.ofNullable((Float) CLUSTER_PREPROCESSING_PERCENTILE.getFrom(namespace)).ifPresent(percentile -> {
+            clusteringBuilder.preprocessor(Preprocessors.PERCENTILE);
+            clusteringBuilder.preprocessorPercentile(percentile);
+        });
+        Optional.ofNullable((Float) CLUSTER_PREPROCESSING_THRESHOLD.getFrom(namespace)).ifPresent(threshold -> {
+            clusteringBuilder.preprocessor(Preprocessors.THRESHOLD);
+            clusteringBuilder.preprocessorPercentile(threshold);
+        });
+        options.setClusteringOptions(clusteringBuilder.build());
+
         return options;
     }
 

+ 30 - 0
jplag/src/main/java/de/jplag/CliGroupHelper.java

@@ -0,0 +1,30 @@
+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;
+
+public class CliGroupHelper {
+
+    private final ArgumentParser parser;
+    private Map<String, MutuallyExclusiveGroup> mutuallyExclusiveGroups = new HashMap<>();
+    private Map<String, ArgumentGroup> argumentGroups = new HashMap<>();
+
+    public CliGroupHelper(ArgumentParser parser) {
+        this.parser = parser;
+    }
+
+    public ArgumentContainer getMutuallyExclusiveGroup(String name) {
+        return mutuallyExclusiveGroups.computeIfAbsent(name, parser::addMutuallyExclusiveGroup);
+    }
+
+    public ArgumentContainer getArgumentGroup(String name) {
+        return argumentGroups.computeIfAbsent(name, parser::addArgumentGroup);
+    }
+
+
+}

+ 103 - 24
jplag/src/main/java/de/jplag/CommandLineArgument.java

@@ -3,15 +3,24 @@ package de.jplag;
 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.TopDownHierarchicalClustering;
 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;
+import net.sourceforge.argparse4j.inf.ArgumentContainer;
 import net.sourceforge.argparse4j.inf.ArgumentParser;
 import net.sourceforge.argparse4j.inf.Namespace;
 
@@ -20,43 +29,60 @@ import net.sourceforge.argparse4j.inf.Namespace;
  * @author Timur Saglam
  */
 public enum CommandLineArgument {
+
     ROOT_DIRECTORY("rootDir", String.class),
-    LANGUAGE("-l", String.class, LanguageOption.getDefault().getDisplayName(), LanguageOption.getAllDisplayNames()),
+    LANGUAGE(new Builder("-l", String.class).defaultsTo(LanguageOption.getDefault().getDisplayName()).choices(LanguageOption.getAllDisplayNames())),
     BASE_CODE("-bc", String.class),
-    VERBOSITY("-v", String.class, "quiet", 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),
     EXCLUDE_FILE("-x", String.class),
     MIN_TOKEN_MATCH("-t", Integer.class),
-    SIMILARITY_THRESHOLD("-m", Float.class, DEFAULT_SIMILARITY_THRESHOLD),
-    SHOWN_COMPARISONS("-n", Integer.class, DEFAULT_SHOWN_COMPARISONS),
-    RESULT_FOLDER("-r", String.class, "result"),
-    COMPARISON_MODE("-c", String.class, DEFAULT_COMPARISON_MODE.getName(), ComparisonMode.allNames());
+    SIMILARITY_THRESHOLD(new Builder("-m", Float.class).defaultsTo(DEFAULT_SIMILARITY_THRESHOLD)),
+    SHOWN_COMPARISONS(new Builder("-n", Integer.class).defaultsTo(DEFAULT_SHOWN_COMPARISONS)),
+    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", TopDownHierarchicalClustering.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 String description;
     private final Optional<Object> defaultValue;
     private final Optional<Collection<String>> choices;
+    private final Optional<String> argumentGroup;
+    private final Optional<String> mutuallyExclusiveGroup;
+    private final Optional<ArgumentAction> action;
+    private final Optional<String> metaVar;
     private final Class<?> type;
 
     private CommandLineArgument(String flag, Class<?> type) {
-        this(flag, type, Optional.empty(), Optional.empty());
-    }
-
-    private CommandLineArgument(String flag, Class<?> type, Object defaultValue) {
-        this(flag, type, Optional.of(defaultValue), Optional.empty());
-    }
-
-    private CommandLineArgument(String flag, Class<?> type, Object defaultValue, Collection<String> choices) {
-        this(flag, type, Optional.of(defaultValue), Optional.of(choices));
+        this(new Builder(flag, type));
     }
 
-    private CommandLineArgument(String flag, Class<?> type, Optional<Object> defaultValue, Optional<Collection<String>> choices) {
-        this.flag = flag;
-        this.type = type;
-        this.defaultValue = defaultValue;
-        this.choices = choices;
+    private CommandLineArgument(Builder builder) {
+        this.flag = builder.flag;
+        this.type = builder.type;
+        this.defaultValue = builder.defaultValue;
+        this.choices = builder.choices;
+        this.argumentGroup = builder.argumentGroup;
+        this.mutuallyExclusiveGroup = builder.mutuallyExclusiveGroup;
+        this.action = builder.action;
+        this.metaVar = builder.metaVar;
         this.description = retrieveDescriptionFromMessages();
     }
 
@@ -68,10 +94,10 @@ public enum CommandLineArgument {
     }
 
     /**
-     * @return the flag name of the command line argument without leading dashes.
+     * @return the flag name of the command line argument without leading dashes and inner dashes replaced with underscores.
      */
     public String flagWithoutDash() {
-        return flag.replace("-", "");
+        return flag.replaceAll("^-+", "").replaceAll("-", "_");
     }
 
     /**
@@ -89,10 +115,17 @@ public enum CommandLineArgument {
      * Parses the command line argument with a specific parser.
      * @param parser is that parser.
      */
-    public void parseWith(ArgumentParser parser) {
-        Argument argument = parser.addArgument(flag).help(description);
+    public void parseWith(ArgumentParser parser, CliGroupHelper groupHelper) {
+        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));
         defaultValue.ifPresent(it -> argument.setDefault(it));
+        action.ifPresent(argument::action);
+        metaVar.ifPresent(argument::metavar);
         argument.type(type);
         if (type == Boolean.class) {
             argument.action(storeTrue());
@@ -111,4 +144,50 @@ public enum CommandLineArgument {
         }
         return Messages.getString(getClass().getSimpleName() + "." + builder.toString());
     }
+
+    private static class Builder {
+        private final String flag;
+        private final Class<?> type;
+        private Optional<Object> defaultValue = Optional.empty();
+        private Optional<Collection<String>> choices = Optional.empty();
+        private Optional<String> argumentGroup = Optional.empty();
+        private Optional<String> mutuallyExclusiveGroup = Optional.empty();
+        private Optional<ArgumentAction> action = Optional.empty();
+        private Optional<String> metaVar = Optional.empty();
+
+        public Builder(String flag, Class<?> type) {
+            this.flag = flag;
+            this.type = type;
+        }
+
+        public Builder defaultsTo(Object defaultValue) {
+            this.defaultValue = Optional.of(defaultValue);
+            return this;
+        }
+
+        public Builder choices(Collection<String> choices) {
+            this.choices = Optional.of(choices);
+            return this;
+        }
+
+        public Builder argumentGroup(String argumentGroup) {
+            this.argumentGroup = Optional.of(argumentGroup);
+            return this;
+        }
+
+        public Builder mutuallyExclusiveGroup(String mutuallyExclusiveGroup) {
+            this.mutuallyExclusiveGroup = Optional.of(mutuallyExclusiveGroup);
+            return this;
+        }
+
+        public Builder action(ArgumentAction action) {
+            this.action = Optional.of(action);
+            return this;
+        }
+
+        public Builder metaVar(String metaVar) {
+            this.metaVar = Optional.of(metaVar);
+            return this;
+        }
+    }
 }

+ 14 - 0
jplag/src/main/resources/de/jplag/messages.properties

@@ -11,3 +11,17 @@ CommandLineArgument.ShownComparisons=The maximum number of comparisons that will
 CommandLineArgument.SimilarityThreshold=Comparison similarity threshold [0-100]: All comparisons above this threshold will be saved
 CommandLineArgument.Subdirectory=Look in directories <root-dir>/*/<dir> for programs
 CommandLineArgument.Verbosity=Verbosity of the logging
+CommandLineArgument.ClusterEnable=Skips the clustering
+CommandLineArgument.ClusterAlgorithm=Which clustering algorithm to use. Agglomerative merges similar submissions bottom up. Spectral clustering is combined with Bayesian Optimization to execute the k-Means clustering algorithm multiple times, hopefully finding a "good" clustering automatically.
+CommandLineArgument.ClusterMetric=The metric used for clustering. AVG is intersection over union, MAX can expose some attempts of obfuscation.
+CommandLineArgument.ClusterSpectralBandwidth=Bandwidth of the matern kernel in the Gaussian Process used during the search for a good number of clusters for spectral clustering. If a good clustering result is found during the search, numbers of clusters that differ by something in range of the bandwidth are also expected to good.
+CommandLineArgument.ClusterSpectralNoise=The result of each run in the search for good clusterings are random. The noise level models the variance in the "worth" of these results. It also acts as a regularization constant.
+CommandLineArgument.ClusterSpectralMinRuns=Minimum number of k-Means executions during spectral clustering. With these initial clustering sizes are explored.
+CommandLineArgument.ClusterSpectralMaxRuns=Maximum number of k-Means executions during spectral clustering. Any execution after the initial runs tries to balance between exploration of unknown clustering sizes and exploitation of clustering sizes known as good.
+CommandLineArgument.ClusterSpectralKmeansIterations=Maximum number of iterations during each execution of the k-Means algorithm.
+CommandLineArgument.ClusterAgglomerativeThreshold=Only clusters with an inter-cluster-similarity greater than this threshold are merged during agglomerative clustering.
+CommandLineArgument.ClusterAgglomerativeInterClusterSimilarity=How to measure the similarity of two clusters during agglomerative clustering. Minimum, maximum or average similarity between the submissions in each cluster.
+CommandLineArgument.ClusterPreprocessingNone=Do not use any preprocessing before clustering. Not recommended for spectral clustering.
+CommandLineArgument.ClusterPreprocessingCdf=Before clustering, the value of the cumulative distribution function of all similarities is estimated. The similarities are multiplied with these estimates. This has the effect of supressing similarities that are low compared to other similarities.
+CommandLineArgument.ClusterPreprocessingPercentile=Any similarity smaller than the given percentile will be suppressed during clustering.
+CommandLineArgument.ClusterPreprocessingThreshold=Any similarity smaller than the given threshold value will be suppressed during clustering.