Skip to content

Commit

Permalink
Merge pull request #3 from madmike200590/pr207_polishing
Browse files Browse the repository at this point in the history
Pr207 polishing
  • Loading branch information
madmike200590 committed Sep 30, 2020
2 parents 81987df + 016b1cb commit 57e12df
Show file tree
Hide file tree
Showing 47 changed files with 639 additions and 757 deletions.
38 changes: 18 additions & 20 deletions src/main/java/at/ac/tuwien/kr/alpha/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,6 @@
*/
package at.ac.tuwien.kr.alpha;

import org.antlr.v4.runtime.RecognitionException;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import at.ac.tuwien.kr.alpha.api.Alpha;
import at.ac.tuwien.kr.alpha.common.AnswerSet;
import at.ac.tuwien.kr.alpha.common.AnswerSetFormatter;
Expand All @@ -60,6 +44,21 @@
import at.ac.tuwien.kr.alpha.config.InputConfig;
import at.ac.tuwien.kr.alpha.solver.Solver;
import at.ac.tuwien.kr.alpha.solver.SolverMaintainingStatistics;
import org.antlr.v4.runtime.RecognitionException;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Main entry point for Alpha.
Expand Down Expand Up @@ -153,12 +152,12 @@ private static void writeComponentGraph(ComponentGraph cg, String path) {
/**
* Writes the given {@link InternalProgram} to the destination passed as the second parameter
*
* @param cg the program to write
* @param prg the program to write
* @param path the path to write the program to
*/
private static void writeInternalProgram(InternalProgram prg, String path) {
LOGGER.debug("Writing preprocessed program to {}", path);
PrintStream ps = null;
PrintStream ps;
try {
if (path.equals(InputConfig.PREPROC_STDOUT_PATH)) {
ps = System.out;
Expand All @@ -172,8 +171,7 @@ private static void writeInternalProgram(InternalProgram prg, String path) {
}
}

private static void computeAndConsumeAnswerSets(Alpha alpha, InputConfig inputCfg,
InternalProgram program) {
private static void computeAndConsumeAnswerSets(Alpha alpha, InputConfig inputCfg, InternalProgram program) {
Solver solver = alpha.prepareSolverFor(program, inputCfg.getFilter());
Stream<AnswerSet> stream = solver.stream();
if (alpha.getConfig().isSortAnswerSets()) {
Expand Down
105 changes: 51 additions & 54 deletions src/main/java/at/ac/tuwien/kr/alpha/api/Alpha.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,6 @@
*/
package at.ac.tuwien.kr.alpha.api;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import at.ac.tuwien.kr.alpha.Util;
import at.ac.tuwien.kr.alpha.common.AnswerSet;
import at.ac.tuwien.kr.alpha.common.AtomStore;
Expand All @@ -63,12 +47,27 @@
import at.ac.tuwien.kr.alpha.grounder.transformation.StratifiedEvaluation;
import at.ac.tuwien.kr.alpha.solver.Solver;
import at.ac.tuwien.kr.alpha.solver.SolverFactory;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Alpha {

private static final Logger LOGGER = LoggerFactory.getLogger(Alpha.class);

private SystemConfig config = new SystemConfig(); // config is initialized with default values
private SystemConfig config = new SystemConfig(); // The config is initialized with default values.

public Alpha(SystemConfig cfg) {
this.config = cfg;
Expand All @@ -81,18 +80,18 @@ public InputProgram readProgram(InputConfig cfg) throws IOException {
InputProgram.Builder prgBuilder = InputProgram.builder();
InputProgram tmpProg;
if (!cfg.getFiles().isEmpty()) {
tmpProg = this.readProgramFiles(cfg.isLiterate(), cfg.getPredicateMethods(), cfg.getFiles());
tmpProg = readProgramFiles(cfg.isLiterate(), cfg.getPredicateMethods(), cfg.getFiles());
prgBuilder.accumulate(tmpProg);
}
if (!cfg.getAspStrings().isEmpty()) {
tmpProg = this.readProgramString(StringUtils.join(cfg.getAspStrings(), System.lineSeparator()), cfg.getPredicateMethods());
tmpProg = readProgramString(StringUtils.join(cfg.getAspStrings(), System.lineSeparator()), cfg.getPredicateMethods());
prgBuilder.accumulate(tmpProg);
}
return prgBuilder.build();
}

public InputProgram readProgramFiles(boolean literate, Map<String, PredicateInterpretation> externals, List<String> paths) throws IOException {
return this.readProgramFiles(literate, externals, paths.stream().map(Paths::get).collect(Collectors.toList()).toArray(new Path[] {}));
return readProgramFiles(literate, externals, paths.stream().map(Paths::get).collect(Collectors.toList()).toArray(new Path[] {}));
}

public InputProgram readProgramFiles(boolean literate, Map<String, PredicateInterpretation> externals, Path... paths) throws IOException {
Expand All @@ -118,17 +117,17 @@ public InputProgram readProgramString(String aspString, Map<String, PredicateInt
}

public InputProgram readProgramString(String aspString) {
return this.readProgramString(aspString, null);
return readProgramString(aspString, null);
}

public NormalProgram normalizeProgram(InputProgram program) {
return new NormalizeProgramTransformation(this.config.isUseNormalizationGrid()).apply(program);
return new NormalizeProgramTransformation(config.isUseNormalizationGrid()).apply(program);
}

public InternalProgram performProgramPreprocessing(InternalProgram program) {
LOGGER.debug("Preprocessing InternalProgram!");
InternalProgram retVal = program;
if (this.config.isEvaluateStratifiedPart()) {
if (config.isEvaluateStratifiedPart()) {
AnalyzedProgram analyzed = new AnalyzedProgram(program.getRules(), program.getFacts());
retVal = new StratifiedEvaluation().apply(analyzed);
}
Expand All @@ -138,88 +137,86 @@ public InternalProgram performProgramPreprocessing(InternalProgram program) {
public InternalProgram performProgramPreprocessing(AnalyzedProgram program) {
LOGGER.debug("Preprocessing AnalyzedProgram!");
InternalProgram retVal = program;
if (this.config.isEvaluateStratifiedPart()) {
if (config.isEvaluateStratifiedPart()) {
retVal = new StratifiedEvaluation().apply(program);
}
return retVal;
}

/**
* Convenience method - overloaded version of solve({@link InternalProgram}) for cases where details of the program
* analysis and normalization aren't of interest
* Convenience method - overloaded version of solve({@link InternalProgram}) for cases where details of the
* program analysis and normalization aren't of interest.
*/
public Stream<AnswerSet> solve(InputProgram program) {
return this.solve(program, InputConfig.DEFAULT_FILTER);
return solve(program, InputConfig.DEFAULT_FILTER);
}

/**
* Convenience method - overloaded version of solve({@link InternalProgram}, {@link Predicate}) for cases where details
* of the program analysis and
* normalization aren't of interest
* Convenience method - overloaded version of solve({@link InternalProgram}, {@link Predicate}) for cases where
* details of the program analysis and normalization aren't of interest.
*/
public Stream<AnswerSet> solve(InputProgram program, java.util.function.Predicate<Predicate> filter) {
NormalProgram normalized = this.normalizeProgram(program);
return this.solve(normalized, filter);
NormalProgram normalized = normalizeProgram(program);
return solve(normalized, filter);
}

/**
* Convenience method - overloaded version of solve({@link InternalProgram}) for cases where details of the program
* analysis aren't of interest
* Convenience method - overloaded version of solve({@link InternalProgram}) for cases where details of the
* program analysis aren't of interest.
*/
public Stream<AnswerSet> solve(NormalProgram program, java.util.function.Predicate<Predicate> filter) {
InternalProgram preprocessed = this.performProgramPreprocessing(InternalProgram.fromNormalProgram(program));
return this.solve(preprocessed, filter);
InternalProgram preprocessed = performProgramPreprocessing(InternalProgram.fromNormalProgram(program));
return solve(preprocessed, filter);
}

/**
* Overloaded version of solve({@link InternalProgram}, {@link Predicate}) that uses a default filter (accept
* everything)
* everything).
*
* @param program the program to solve
* @return a stream of answer sets
*/
public Stream<AnswerSet> solve(InternalProgram program) {
return this.solve(program, InputConfig.DEFAULT_FILTER);
return solve(program, InputConfig.DEFAULT_FILTER);
}

/**
* Solves the given program and filters answer sets based on the passed predicate
* Solves the given program and filters answer sets based on the passed predicate.
*
* @param program an {@link InternalProgram} to solve
* @param filter {@link Predicate} filtering {@at.ac.tuwien.kr.alpha.common.Predicate}s in the returned answer sets
* @return a Stream of answer sets representing stable models of the given program
*/
public Stream<AnswerSet> solve(InternalProgram program, java.util.function.Predicate<Predicate> filter) {
Stream<AnswerSet> retVal = this.prepareSolverFor(program, filter).stream();
return this.config.isSortAnswerSets() ? retVal.sorted() : retVal;
Stream<AnswerSet> retVal = prepareSolverFor(program, filter).stream();
return config.isSortAnswerSets() ? retVal.sorted() : retVal;
}

/**
* Prepares a solver (and accompanying grounder) instance pre-loaded with the given program. Use this if the solver is
* needed after reading answer sets
* (e.g. for obtaining statistics)
* Prepares a solver (and accompanying grounder) instance pre-loaded with the given program. Use this if the
* solver is needed after reading answer sets (e.g. for obtaining statistics).
*
* @param program the program to solve
* @param filter a (java util) predicate that filters (asp-)predicates which should be contained in the answer set
* stream from the solver
* @return a solver (and accompanying grounder) instance pre-loaded with the given program
* @param program the program to solve.
* @param filter a (java util) predicate that filters (asp-)predicates which should be contained in the answer
* set stream from the solver.
* @return a solver (and accompanying grounder) instance pre-loaded with the given program.
*/
public Solver prepareSolverFor(InternalProgram program, java.util.function.Predicate<Predicate> filter) {
String grounderName = this.config.getGrounderName();
boolean doDebugChecks = this.config.isDebugInternalChecks();
String grounderName = config.getGrounderName();
boolean doDebugChecks = config.isDebugInternalChecks();

GrounderHeuristicsConfiguration grounderHeuristicConfiguration = GrounderHeuristicsConfiguration
.getInstance(this.config.getGrounderToleranceConstraints(), this.config.getGrounderToleranceRules());
grounderHeuristicConfiguration.setAccumulatorEnabled(this.config.isGrounderAccumulatorEnabled());
.getInstance(config.getGrounderToleranceConstraints(), config.getGrounderToleranceRules());
grounderHeuristicConfiguration.setAccumulatorEnabled(config.isGrounderAccumulatorEnabled());

AtomStore atomStore = new AtomStoreImpl();
Grounder grounder = GrounderFactory.getInstance(grounderName, program, atomStore, filter, grounderHeuristicConfiguration, doDebugChecks);

return SolverFactory.getInstance(this.config, atomStore, grounder);
return SolverFactory.getInstance(config, atomStore, grounder);
}

public SystemConfig getConfig() {
return this.config;
return config;
}

public void setConfig(SystemConfig config) {
Expand Down
29 changes: 14 additions & 15 deletions src/main/java/at/ac/tuwien/kr/alpha/api/externals/Externals.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,6 @@
*/
package at.ac.tuwien.kr.alpha.api.externals;

import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import at.ac.tuwien.kr.alpha.api.externals.stdlib.AspStandardLibrary;
import at.ac.tuwien.kr.alpha.common.atoms.Atom;
import at.ac.tuwien.kr.alpha.common.atoms.BasicAtom;
Expand All @@ -49,10 +37,21 @@
import at.ac.tuwien.kr.alpha.common.fixedinterpretations.SuppliedPredicateInterpretation;
import at.ac.tuwien.kr.alpha.common.fixedinterpretations.UnaryPredicateInterpretation;
import at.ac.tuwien.kr.alpha.common.terms.ConstantTerm;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public final class Externals {

// private constructor since this is a utility class
// Private constructor since this is a utility class.
private Externals() {

}
Expand Down Expand Up @@ -142,10 +141,10 @@ public static PredicateInterpretation processPredicate(java.util.function.Suppli
* @return a list of {@link Atom}s.
*/
public static <T extends Comparable<T>> List<Atom> asFacts(Class<T> classOfExtFacts, Collection<T> extFacts) {
// use Class<T> as parameter here, taking simple name from first element might not give desired result if it's a subtype
// Use Class<T> as parameter here, taking simple name from first element might not give desired result if it is a subtype.
List<Atom> retVal = new ArrayList<>();
String javaName = classOfExtFacts.getSimpleName();
String name = javaName.substring(0, 1).toLowerCase() + javaName.substring(1); // camel-cased, but starting with lower case letter
String name = javaName.substring(0, 1).toLowerCase() + javaName.substring(1); // Camel-cased, but starting with lower case letter.
for (T instance : extFacts) {
retVal.add(new BasicAtom(at.ac.tuwien.kr.alpha.common.Predicate.getInstance(name, 1), ConstantTerm.getInstance(instance)));
}
Expand Down

0 comments on commit 57e12df

Please sign in to comment.