diff --git a/src/main/java/com/booleworks/logicng/backbones/BackboneGeneration.java b/src/main/java/com/booleworks/logicng/backbones/BackboneGeneration.java index 08bd13c8..a4493b48 100644 --- a/src/main/java/com/booleworks/logicng/backbones/BackboneGeneration.java +++ b/src/main/java/com/booleworks/logicng/backbones/BackboneGeneration.java @@ -8,6 +8,7 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.BackboneFunction; @@ -46,16 +47,16 @@ private BackboneGeneration() { * @return the backbone or {@code null} if the computation was aborted by * the handler */ - public static Backbone compute(final FormulaFactory f, final Collection formulas, - final Collection variables, final BackboneType type, - final ComputationHandler handler) { + public static LNGResult compute(final FormulaFactory f, final Collection formulas, + final Collection variables, final BackboneType type, + final ComputationHandler handler) { if (formulas == null || formulas.isEmpty()) { throw new IllegalArgumentException("Provide at least one formula for backbone computation"); } final SATSolver solver = SATSolver.newSolver(f, SATSolverConfig.builder().cnfMethod(SATSolverConfig.CNFMethod.PG_ON_SOLVER).build()); solver.add(formulas); - return solver.execute(BackboneFunction.builder().handler(handler).variables(variables).type(type).build()); + return solver.execute(BackboneFunction.builder().variables(variables).type(type).build(), handler); } /** @@ -70,7 +71,7 @@ public static Backbone compute(final FormulaFactory f, final Collection */ public static Backbone compute(final FormulaFactory f, final Collection formulas, final Collection variables, final BackboneType type) { - return compute(f, formulas, variables, type, NopHandler.get()); + return compute(f, formulas, variables, type, NopHandler.get()).getResult(); } /** @@ -120,8 +121,8 @@ public static Backbone compute(final FormulaFactory f, final Collection * @param type the type of backbone variables that should be computed * @return the backbone */ - public static Backbone compute(final FormulaFactory f, final Formula formula, final Collection variables, - final BackboneType type) { + public static Backbone compute(final FormulaFactory f, final Formula formula, + final Collection variables, final BackboneType type) { return compute(f, Collections.singletonList(formula), variables, type); } diff --git a/src/main/java/com/booleworks/logicng/explanations/mus/DeletionBasedMUS.java b/src/main/java/com/booleworks/logicng/explanations/mus/DeletionBasedMUS.java index adf8dc08..7a29f444 100644 --- a/src/main/java/com/booleworks/logicng/explanations/mus/DeletionBasedMUS.java +++ b/src/main/java/com/booleworks/logicng/explanations/mus/DeletionBasedMUS.java @@ -5,11 +5,11 @@ package com.booleworks.logicng.explanations.mus; import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.MUS_COMPUTATION_STARTED; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.SolverState; @@ -25,9 +25,12 @@ public final class DeletionBasedMUS extends MUSAlgorithm { @Override - public UNSATCore computeMUS(final FormulaFactory f, final List propositions, - final MUSConfig config) { - config.handler.shouldResume(MUS_COMPUTATION_STARTED); + public LNGResult> computeMUS( + final FormulaFactory f, final List propositions, + final MUSConfig config, final ComputationHandler handler) { + if (!handler.shouldResume(MUS_COMPUTATION_STARTED)) { + return LNGResult.aborted(MUS_COMPUTATION_STARTED); + } final List mus = new ArrayList<>(propositions.size()); final List solverStates = new ArrayList<>(propositions.size()); final SATSolver solver = SATSolver.newSolver(f); @@ -35,11 +38,11 @@ public UNSATCore computeMUS(final FormulaFactory f, f solverStates.add(solver.saveState()); solver.add(proposition); } - boolean sat = solver.satCall().handler(config.handler).sat() == Tristate.TRUE; - if (!config.handler.shouldResume(NO_EVENT)) { - return null; + LNGResult sat = solver.satCall().handler(handler).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); } - if (sat) { + if (sat.getResult()) { throw new IllegalArgumentException("Cannot compute a MUS for a satisfiable formula set."); } for (int i = solverStates.size() - 1; i >= 0; i--) { @@ -47,14 +50,14 @@ public UNSATCore computeMUS(final FormulaFactory f, f for (final Proposition prop : mus) { solver.add(prop); } - sat = solver.satCall().handler(config.handler).sat() == Tristate.TRUE; - if (!config.handler.shouldResume(NO_EVENT)) { - return null; + sat = solver.satCall().handler(handler).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); } - if (sat) { + if (sat.getResult()) { mus.add(propositions.get(i)); } } - return new UNSATCore<>(mus, true); + return LNGResult.of(new UNSATCore<>(mus, true)); } } diff --git a/src/main/java/com/booleworks/logicng/explanations/mus/MUSAlgorithm.java b/src/main/java/com/booleworks/logicng/explanations/mus/MUSAlgorithm.java index f000522e..1c958391 100644 --- a/src/main/java/com/booleworks/logicng/explanations/mus/MUSAlgorithm.java +++ b/src/main/java/com/booleworks/logicng/explanations/mus/MUSAlgorithm.java @@ -6,13 +6,16 @@ import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.propositions.Proposition; import java.util.List; /** * Abstract super class for MUS computation algorithms. - * @version 2.1.0 + * @version 3.0.0 * @since 1.1 */ abstract class MUSAlgorithm { @@ -23,9 +26,28 @@ abstract class MUSAlgorithm { * @param f the formula factory * @param propositions the propositions * @param config the MUS configuration - * @return the MUS or null if the MUS computation was configured with a - * handler and this handler aborted the computation + * @param handler the computation handler + * @return an LNG result containing the MUS (unless the handler aborted + * the computation) + * @throws IllegalArgumentException if the set of propositions is + * satisfiable */ - public abstract UNSATCore computeMUS(final FormulaFactory f, final List propositions, - final MUSConfig config); + public abstract LNGResult> computeMUS( + final FormulaFactory f, final List propositions, + final MUSConfig config, final ComputationHandler handler); + + /** + * Computes a MUS for the given propositions. + * @param the type of the MUSes propositions + * @param f the formula factory + * @param propositions the propositions + * @param config the MUS configuration + * @return the MUS + * @throws IllegalArgumentException if the set of propositions is + * satisfiable + */ + public UNSATCore computeMUS( + final FormulaFactory f, final List propositions, final MUSConfig config) { + return computeMUS(f, propositions, config, NopHandler.get()).getResult(); + } } diff --git a/src/main/java/com/booleworks/logicng/explanations/mus/MUSConfig.java b/src/main/java/com/booleworks/logicng/explanations/mus/MUSConfig.java index 8adf4360..e5816ee6 100644 --- a/src/main/java/com/booleworks/logicng/explanations/mus/MUSConfig.java +++ b/src/main/java/com/booleworks/logicng/explanations/mus/MUSConfig.java @@ -6,8 +6,6 @@ import com.booleworks.logicng.configurations.Configuration; import com.booleworks.logicng.configurations.ConfigurationType; -import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; /** * The configuration object for the MUS generation. @@ -25,7 +23,6 @@ public enum Algorithm { } final Algorithm algorithm; - final ComputationHandler handler; /** * Constructs a new configuration with a given type. @@ -34,7 +31,6 @@ public enum Algorithm { private MUSConfig(final Builder builder) { super(ConfigurationType.MUS); algorithm = builder.algorithm; - handler = builder.handler; } /** @@ -59,7 +55,6 @@ public String toString() { public static class Builder { private Algorithm algorithm = Algorithm.DELETION; - private ComputationHandler handler = NopHandler.get(); private Builder() { // Initialize only via factory @@ -76,16 +71,6 @@ public Builder algorithm(final Algorithm algorithm) { return this; } - /** - * Sets the SAT handler for the MUS generation. - * @param handler the SAT handler - * @return the current builder - */ - public Builder handler(final ComputationHandler handler) { - this.handler = handler; - return this; - } - /** * Builds the configuration. * @return the configuration. diff --git a/src/main/java/com/booleworks/logicng/explanations/mus/MUSGeneration.java b/src/main/java/com/booleworks/logicng/explanations/mus/MUSGeneration.java index c36dacba..9b0db50b 100644 --- a/src/main/java/com/booleworks/logicng/explanations/mus/MUSGeneration.java +++ b/src/main/java/com/booleworks/logicng/explanations/mus/MUSGeneration.java @@ -7,6 +7,9 @@ import com.booleworks.logicng.configurations.ConfigurationType; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.propositions.Proposition; import java.util.List; @@ -53,14 +56,30 @@ public UNSATCore computeMUS(final FormulaFactory f, f */ public UNSATCore computeMUS(final FormulaFactory f, final List propositions, final MUSConfig config) { + return computeMUS(f, propositions, config, NopHandler.get()).getResult(); + } + + /** + * Computes a MUS for the given propositions and the given configuration of + * the MUS generation. + * @param the type of the MUSes propositions + * @param f the formula factory + * @param propositions the propositions + * @param config the MUS configuration + * @param handler the computation handler + * @return the MUS + */ + public LNGResult> computeMUS( + final FormulaFactory f, final List propositions, + final MUSConfig config, final ComputationHandler handler) { if (propositions.isEmpty()) { throw new IllegalArgumentException("Cannot generate a MUS for an empty list of propositions"); } switch (config.algorithm) { case PLAIN_INSERTION: - return insertion.computeMUS(f, propositions, config); + return insertion.computeMUS(f, propositions, config, handler); case DELETION: - return deletion.computeMUS(f, propositions, config); + return deletion.computeMUS(f, propositions, config, handler); default: throw new IllegalStateException("Unknown MUS algorithm: " + config.algorithm); } diff --git a/src/main/java/com/booleworks/logicng/explanations/mus/PlainInsertionBasedMUS.java b/src/main/java/com/booleworks/logicng/explanations/mus/PlainInsertionBasedMUS.java index 300709af..55ac8b8f 100644 --- a/src/main/java/com/booleworks/logicng/explanations/mus/PlainInsertionBasedMUS.java +++ b/src/main/java/com/booleworks/logicng/explanations/mus/PlainInsertionBasedMUS.java @@ -5,12 +5,11 @@ package com.booleworks.logicng.explanations.mus; import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.MUS_COMPUTATION_STARTED; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.solvers.SATSolver; @@ -25,9 +24,12 @@ public class PlainInsertionBasedMUS extends MUSAlgorithm { @Override - public UNSATCore computeMUS(final FormulaFactory f, final List propositions, - final MUSConfig config) { - config.handler.shouldResume(MUS_COMPUTATION_STARTED); + public LNGResult> computeMUS( + final FormulaFactory f, final List propositions, + final MUSConfig config, final ComputationHandler handler) { + if (!handler.shouldResume(MUS_COMPUTATION_STARTED)) { + return LNGResult.aborted(MUS_COMPUTATION_STARTED); + } final List currentFormula = new ArrayList<>(propositions.size()); currentFormula.addAll(propositions); final List mus = new ArrayList<>(propositions.size()); @@ -39,7 +41,14 @@ public UNSATCore computeMUS(final FormulaFactory f, f solver.add(p); } int count = currentFormula.size(); - while (shouldProceed(solver, config.handler)) { + while (true) { + final LNGResult sat = solver.satCall().handler(handler).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); + } + if (!sat.getResult()) { + break; + } if (count == 0) { throw new IllegalArgumentException("Cannot compute a MUS for a satisfiable formula set."); } @@ -48,9 +57,6 @@ public UNSATCore computeMUS(final FormulaFactory f, f transitionProposition = removeProposition; solver.add(removeProposition); } - if (!config.handler.shouldResume(NO_EVENT)) { - return null; - } currentFormula.clear(); currentFormula.addAll(currentSubset); if (transitionProposition != null) { @@ -58,11 +64,7 @@ public UNSATCore computeMUS(final FormulaFactory f, f mus.add(transitionProposition); } } - return new UNSATCore<>(mus, true); + return LNGResult.of(new UNSATCore<>(mus, true)); } - private static boolean shouldProceed(final SATSolver solver, final ComputationHandler handler) { - final boolean sat = solver.satCall().handler(handler).sat() == Tristate.TRUE; - return sat && handler.shouldResume(NO_EVENT); - } } diff --git a/src/main/java/com/booleworks/logicng/explanations/smus/SmusComputation.java b/src/main/java/com/booleworks/logicng/explanations/smus/SmusComputation.java index c4bcd114..49ae6ae2 100644 --- a/src/main/java/com/booleworks/logicng/explanations/smus/SmusComputation.java +++ b/src/main/java/com/booleworks/logicng/explanations/smus/SmusComputation.java @@ -4,16 +4,17 @@ package com.booleworks.logicng.explanations.smus; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; +import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.SMUS_COMPUTATION_STARTED; import com.booleworks.logicng.datastructures.Assignment; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; -import com.booleworks.logicng.handlers.events.ComputationStartedEvent; +import com.booleworks.logicng.handlers.SatResult; +import com.booleworks.logicng.handlers.UnsatResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.propositions.StandardProposition; import com.booleworks.logicng.solvers.SATSolver; @@ -59,9 +60,10 @@ private SmusComputation() { * @return the SMUS or {@code null} if the given propositions are * satisfiable or the handler aborted the computation */ - public static

List

computeSmus(final FormulaFactory f, final List

propositions, - final List additionalConstraints) { - return computeSmus(f, propositions, additionalConstraints, NopHandler.get()); + public static

UnsatResult> computeSmus( + final FormulaFactory f, final List

propositions, + final List additionalConstraints) { + return computeSmus(f, propositions, additionalConstraints, NopHandler.get()).getResult(); } /** @@ -80,10 +82,12 @@ public static

List

computeSmus(final FormulaFactory f * @return the SMUS or {@code null} if the given propositions are * satisfiable or the handler aborted the computation */ - public static

List

computeSmus(final FormulaFactory f, final List

propositions, - final List additionalConstraints, - final ComputationHandler handler) { - handler.shouldResume(ComputationStartedEvent.SMUS_COMPUTATION_STARTED); + public static

LNGResult>> computeSmus( + final FormulaFactory f, final List

propositions, + final List additionalConstraints, final ComputationHandler handler) { + if (!handler.shouldResume(SMUS_COMPUTATION_STARTED)) { + return LNGResult.aborted(SMUS_COMPUTATION_STARTED); + } final SATSolver growSolver = SATSolver.newSolver(f); growSolver.add(additionalConstraints == null ? Collections.singletonList(f.verum()) : additionalConstraints); final Map propositionMapping = new TreeMap<>(); @@ -92,24 +96,34 @@ public static

List

computeSmus(final FormulaFactory f propositionMapping.put(selector, proposition); growSolver.add(f.equivalence(selector, proposition.formula())); } - final boolean sat = growSolver.satCall().handler(handler).addFormulas(propositionMapping.keySet()).sat() == Tristate.TRUE; - if (sat || !handler.shouldResume(NO_EVENT)) { - return null; + final LNGResult sat = + growSolver.satCall().handler(handler).addFormulas(propositionMapping.keySet()).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); + } else if (sat.getResult()) { + return LNGResult.of(UnsatResult.sat()); } final SATSolver hSolver = SATSolver.newSolver(f); while (true) { - final SortedSet h = minimumHs(hSolver, propositionMapping.keySet(), handler); - if (h == null || !handler.shouldResume(NO_EVENT)) { - return null; - } - final SortedSet c = grow(growSolver, h, propositionMapping.keySet(), handler); - if (!handler.shouldResume(NO_EVENT)) { - return null; + final LNGResult>> h = + minimumHs(hSolver, propositionMapping.keySet(), handler); + if (!h.isSuccess()) { + return LNGResult.aborted(h.getAbortionEvent()); + } else if (!h.getResult().isSat()) { + return LNGResult.of(UnsatResult.sat()); + } else { + final SortedSet hResult = h.getResult().getResult(); + final LNGResult>> c = + grow(growSolver, hResult, propositionMapping.keySet(), handler); + if (!c.isSuccess()) { + return LNGResult.aborted(c.getAbortionEvent()); + } else if (!c.getResult().isSat()) { + return LNGResult.of(UnsatResult.unsat( + hResult.stream().map(propositionMapping::get).collect(Collectors.toList()))); + } else { + hSolver.add(f.or(c.getResult().getResult())); + } } - if (c == null) { - return h.stream().map(propositionMapping::get).collect(Collectors.toList()); - } - hSolver.add(f.or(c)); } } @@ -122,9 +136,9 @@ public static

List

computeSmus(final FormulaFactory f * @return the SMUS or {@code null} if the given propositions are * satisfiable or the handler aborted the computation */ - public static List computeSmusForFormulas(final FormulaFactory f, final List formulas, - final List additionalConstraints) { - return computeSmusForFormulas(f, formulas, additionalConstraints, NopHandler.get()); + public static UnsatResult> computeSmusForFormulas(final FormulaFactory f, final List formulas, + final List additionalConstraints) { + return computeSmusForFormulas(f, formulas, additionalConstraints, NopHandler.get()).getResult(); } /** @@ -137,39 +151,55 @@ public static List computeSmusForFormulas(final FormulaFactory f, final * @return the SMUS or {@code null} if the given propositions are * satisfiable or the handler aborted the computation */ - public static List computeSmusForFormulas(final FormulaFactory f, final List formulas, - final List additionalConstraints, - final ComputationHandler handler) { + public static LNGResult>> computeSmusForFormulas( + final FormulaFactory f, final List formulas, + final List additionalConstraints, final ComputationHandler handler) { final List props = formulas.stream().map(StandardProposition::new).collect(Collectors.toList()); - final List smus = computeSmus(f, props, additionalConstraints, handler); - return smus == null ? null : smus.stream().map(Proposition::formula).collect(Collectors.toList()); + final LNGResult>> smus = computeSmus(f, props, additionalConstraints, handler); + if (!smus.isSuccess()) { + return LNGResult.aborted(smus.getAbortionEvent()); + } else if (!smus.getResult().isUnsat()) { + return LNGResult.of(UnsatResult.sat()); + } else { + return LNGResult.of(UnsatResult.unsat(smus.getResult().getResult().stream() + .map(Proposition::formula).collect(Collectors.toList()))); + } } - private static SortedSet minimumHs(final SATSolver hSolver, final Set variables, - final ComputationHandler handler) { - final Assignment minimumHsModel = hSolver.execute(OptimizationFunction.builder() - .handler(handler) + private static LNGResult>> minimumHs(final SATSolver hSolver, + final Set variables, + final ComputationHandler handler) { + final LNGResult> minimumHsModel = hSolver.execute(OptimizationFunction.builder() .literals(variables) - .minimize().build()); - return !handler.shouldResume(NO_EVENT) ? null : new TreeSet<>(minimumHsModel.positiveVariables()); + .minimize().build(), handler); + if (!minimumHsModel.isSuccess()) { + return LNGResult.aborted(minimumHsModel.getAbortionEvent()); + } else if (minimumHsModel.getResult().isSat()) { + final SortedSet model = minimumHsModel.getResult().getResult().positiveVariables(); + return LNGResult.of(SatResult.sat(new TreeSet<>(model))); + } else { + return LNGResult.of(SatResult.unsat()); + } } - private static SortedSet grow(final SATSolver growSolver, final SortedSet h, - final Set variables, final ComputationHandler handler) { + private static LNGResult>> grow( + final SATSolver growSolver, final SortedSet h, + final Set variables, final ComputationHandler handler) { final SolverState solverState = growSolver.saveState(); growSolver.add(h); - final Assignment maxModel = growSolver.execute(OptimizationFunction.builder() - .handler(handler) + final LNGResult> maxModel = growSolver.execute(OptimizationFunction.builder() .literals(variables) - .maximize().build()); - if (maxModel == null || !handler.shouldResume(NO_EVENT)) { - return null; + .maximize().build(), handler); + if (!maxModel.isSuccess()) { + return LNGResult.aborted(maxModel.getAbortionEvent()); + } else if (!maxModel.getResult().isSat()) { + return LNGResult.of(SatResult.unsat()); } else { - final SortedSet maximumSatisfiableSet = maxModel.positiveVariables(); + final SortedSet maximumSatisfiableSet = maxModel.getResult().getResult().positiveVariables(); growSolver.loadState(solverState); final SortedSet minimumCorrectionSet = new TreeSet<>(variables); maximumSatisfiableSet.forEach(minimumCorrectionSet::remove); - return minimumCorrectionSet; + return LNGResult.of(SatResult.sat(minimumCorrectionSet)); } } } diff --git a/src/main/java/com/booleworks/logicng/formulas/Formula.java b/src/main/java/com/booleworks/logicng/formulas/Formula.java index 33fbe086..87dbaba7 100644 --- a/src/main/java/com/booleworks/logicng/formulas/Formula.java +++ b/src/main/java/com/booleworks/logicng/formulas/Formula.java @@ -10,7 +10,8 @@ import com.booleworks.logicng.functions.NumberOfAtomsFunction; import com.booleworks.logicng.functions.NumberOfNodesFunction; import com.booleworks.logicng.functions.VariablesFunction; -import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.knowledgecompilation.bdds.BDD; import com.booleworks.logicng.knowledgecompilation.bdds.BDDFactory; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; @@ -71,7 +72,7 @@ default long numberOfNodes(final FormulaFactory f) { * Returns the number of operands of this formula. * @return the number of operands of this formula */ - public abstract int numberOfOperands(); + int numberOfOperands(); /** * Returns the number of internal nodes of this formula. @@ -357,7 +358,7 @@ default BDD bdd(final FormulaFactory f, final VariableOrderingProvider provider) } else { kernel = new BDDKernel(f, provider.getOrder(f, formula), varNum * 30, varNum * 20); } - return BDDFactory.build(f, formula, kernel, NopHandler.get()); + return BDDFactory.build(f, formula, kernel); } /** @@ -382,6 +383,17 @@ default Formula transform(final FormulaTransformation transformation) { return transformation.apply(this); } + /** + * Transforms this formula with a given formula transformation. + * @param transformation the formula transformation + * @param handler the computation handler + * @return the result of the transformation which may have been aborted by + * the computation handler + */ + default LNGResult transform(final FormulaTransformation transformation, final ComputationHandler handler) { + return transformation.apply(this, handler); + } + /** * Evaluates a given predicate on this formula, caches the result, and * returns {@code true} if the predicate holds, {@code false} otherwise. diff --git a/src/main/java/com/booleworks/logicng/formulas/FormulaTransformation.java b/src/main/java/com/booleworks/logicng/formulas/FormulaTransformation.java index fabd4585..ca5edb67 100644 --- a/src/main/java/com/booleworks/logicng/formulas/FormulaTransformation.java +++ b/src/main/java/com/booleworks/logicng/formulas/FormulaTransformation.java @@ -4,6 +4,10 @@ package com.booleworks.logicng.formulas; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.NopHandler; + /** * A transformation on a formula. * @version 3.0.0 @@ -13,9 +17,19 @@ public interface FormulaTransformation { /** - * Returns the transformed formula. + * Performs the transformation with the given handler. + * @param formula the input formula + * @param handler the computation handler + * @return the LNGResult with the transformed formula + */ + LNGResult apply(Formula formula, ComputationHandler handler); + + /** + * Performs the transformation. * @param formula the input formula * @return the transformed formula */ - Formula apply(Formula formula); + default Formula apply(final Formula formula) { + return apply(formula, NopHandler.get()).orElseThrow(() -> new IllegalStateException("Computations should never abort with the NopHandler.")); + } } diff --git a/src/main/java/com/booleworks/logicng/functions/MinimumPrimeImplicantFunction.java b/src/main/java/com/booleworks/logicng/functions/MinimumPrimeImplicantFunction.java index 4c7b9eaf..a09311a8 100644 --- a/src/main/java/com/booleworks/logicng/functions/MinimumPrimeImplicantFunction.java +++ b/src/main/java/com/booleworks/logicng/functions/MinimumPrimeImplicantFunction.java @@ -10,6 +10,7 @@ import com.booleworks.logicng.formulas.FormulaFunction; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.SatResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.OptimizationFunction; import com.booleworks.logicng.solvers.sat.SATSolverConfig; @@ -26,7 +27,7 @@ * @version 3.0.0 * @since 2.0.0 */ -public final class MinimumPrimeImplicantFunction implements FormulaFunction> { +public final class MinimumPrimeImplicantFunction implements FormulaFunction>> { private static final String POS = "_POS"; private static final String NEG = "_NEG"; @@ -37,7 +38,7 @@ public MinimumPrimeImplicantFunction(final FormulaFactory f) { } @Override - public SortedSet apply(final Formula formula) { + public SatResult> apply(final Formula formula) { final Formula nnf = formula.nnf(f); final Map newVar2oldLit = new HashMap<>(); final Map substitution = new HashMap<>(); @@ -57,17 +58,17 @@ public SortedSet apply(final Formula formula) { } } - if (!solver.sat()) { - return null; + final SatResult minimumModel = solver.execute(OptimizationFunction.minimize(newVar2oldLit.keySet())); + if (!minimumModel.isSat()) { + return SatResult.unsat(); } - final Assignment minimumModel = solver.execute(OptimizationFunction.minimize(newVar2oldLit.keySet())); final SortedSet primeImplicant = new TreeSet<>(); - for (final Variable variable : minimumModel.positiveVariables()) { + for (final Variable variable : minimumModel.getResult().positiveVariables()) { final Literal literal = newVar2oldLit.get(variable); if (literal != null) { primeImplicant.add(literal); } } - return primeImplicant; + return SatResult.sat(primeImplicant); } } diff --git a/src/main/java/com/booleworks/logicng/handlers/ComputationHandler.java b/src/main/java/com/booleworks/logicng/handlers/ComputationHandler.java index 363c6e95..79b5e313 100644 --- a/src/main/java/com/booleworks/logicng/handlers/ComputationHandler.java +++ b/src/main/java/com/booleworks/logicng/handlers/ComputationHandler.java @@ -1,11 +1,11 @@ package com.booleworks.logicng.handlers; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * Interface for a computation handler. - * @since 3.0.0 * @version 3.0.0 + * @since 3.0.0 */ public interface ComputationHandler { /** @@ -14,11 +14,5 @@ public interface ComputationHandler { * @param event the event to handle, must not be {@code null} * @return whether the computation should be resumed or not */ - boolean shouldResume(LogicNGEvent event); - - /** - * @deprecated should be removed - */ - @Deprecated - boolean isAborted(); + boolean shouldResume(LNGEvent event); } diff --git a/src/main/java/com/booleworks/logicng/handlers/LNGResult.java b/src/main/java/com/booleworks/logicng/handlers/LNGResult.java new file mode 100644 index 00000000..bba9eecf --- /dev/null +++ b/src/main/java/com/booleworks/logicng/handlers/LNGResult.java @@ -0,0 +1,86 @@ +package com.booleworks.logicng.handlers; + +import com.booleworks.logicng.handlers.events.LNGEvent; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Supplier; + +public class LNGResult { + + protected final RESULT result; + protected final LNGEvent abortionEvent; + + protected LNGResult(final RESULT result, final LNGEvent abortionEvent) { + this.result = result; + this.abortionEvent = abortionEvent; + } + + public static LNGResult of(final RESULT result) { + assert result != null; + return new LNGResult<>(result, null); + } + + public static LNGResult aborted(final LNGEvent event) { + assert event != null; + return new LNGResult<>(null, event); + } + + public RESULT getResult() { + return result; + } + + public LNGEvent getAbortionEvent() { + return abortionEvent; + } + + public boolean isSuccess() { + return abortionEvent == null; + } + + public LNGResult map(final Function transformation) { + return new LNGResult<>(isSuccess() ? transformation.apply(result) : null, abortionEvent); + } + + @SuppressWarnings("unchecked") + public LNGResult flatMap(final Function> transformation) { + return isSuccess() ? (LNGResult) transformation.apply(result) : LNGResult.aborted(abortionEvent); + } + + public RESULT orElse(final RESULT alternative) { + return isSuccess() ? result : alternative; + } + + public RESULT orElseThrow(final Supplier exception) throws X { + if (isSuccess()) { + return result; + } else { + throw exception.get(); + } + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final LNGResult that = (LNGResult) o; + return Objects.equals(result, that.result) && Objects.equals(abortionEvent, that.abortionEvent); + } + + @Override + public int hashCode() { + return Objects.hash(result, abortionEvent); + } + + @Override + public String toString() { + return "ComputationResult{" + + "result=" + result + + ", abortionEvent=" + abortionEvent + + '}'; + } +} diff --git a/src/main/java/com/booleworks/logicng/handlers/LNGResultWithPartial.java b/src/main/java/com/booleworks/logicng/handlers/LNGResultWithPartial.java new file mode 100644 index 00000000..dee15ef4 --- /dev/null +++ b/src/main/java/com/booleworks/logicng/handlers/LNGResultWithPartial.java @@ -0,0 +1,59 @@ +package com.booleworks.logicng.handlers; + +import com.booleworks.logicng.handlers.events.LNGEvent; + +import java.util.Objects; +import java.util.Optional; + +public class LNGResultWithPartial extends LNGResult { + + protected final PARTIAL partialResult; + + protected LNGResultWithPartial(final RESULT result, final PARTIAL partialResult, final LNGEvent abortionEvent) { + super(result, abortionEvent); + this.partialResult = partialResult; + } + + // TODO naming ("of" not possible because of name clash with superclass) + public static LNGResultWithPartial ofResult(final RESULT result) { + return new LNGResultWithPartial<>(result, null, null); + } + + public static LNGResultWithPartial aborted( + final PARTIAL partialResult, final LNGEvent event) { + return new LNGResultWithPartial<>(null, partialResult, event); + } + + public Optional getPartialResult() { + return Optional.ofNullable(partialResult); + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + final LNGResultWithPartial that = (LNGResultWithPartial) o; + return Objects.equals(partialResult, that.partialResult); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), partialResult); + } + + @Override + public String toString() { + return "LNGResultWithPartial{" + + "result=" + result + + ", partialResult=" + partialResult + + ", abortionEvent=" + abortionEvent + + '}'; + } +} diff --git a/src/main/java/com/booleworks/logicng/handlers/NopHandler.java b/src/main/java/com/booleworks/logicng/handlers/NopHandler.java index 8f2233cc..945261f1 100644 --- a/src/main/java/com/booleworks/logicng/handlers/NopHandler.java +++ b/src/main/java/com/booleworks/logicng/handlers/NopHandler.java @@ -1,6 +1,6 @@ package com.booleworks.logicng.handlers; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * A computation handler which never aborts the computation. @@ -25,12 +25,7 @@ public static NopHandler get() { } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { return true; } - - @Override - public boolean isAborted() { - return false; - } } diff --git a/src/main/java/com/booleworks/logicng/handlers/NumberOfModelsHandler.java b/src/main/java/com/booleworks/logicng/handlers/NumberOfModelsHandler.java index e4f569bd..70ecaa7d 100644 --- a/src/main/java/com/booleworks/logicng/handlers/NumberOfModelsHandler.java +++ b/src/main/java/com/booleworks/logicng/handlers/NumberOfModelsHandler.java @@ -6,7 +6,7 @@ import com.booleworks.logicng.handlers.events.ComputationStartedEvent; import com.booleworks.logicng.handlers.events.EnumerationFoundModelsEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.SimpleEvent; /** @@ -17,7 +17,6 @@ */ public class NumberOfModelsHandler implements ComputationHandler { - private boolean aborted = false; private final int bound; private int countCommitted; private int countUncommitted; @@ -37,27 +36,19 @@ public NumberOfModelsHandler(final int bound) { } @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == ComputationStartedEvent.MODEL_ENUMERATION_STARTED) { countCommitted = 0; countUncommitted = 0; } else if (event instanceof EnumerationFoundModelsEvent) { final int numberOfModels = ((EnumerationFoundModelsEvent) event).getNumberOfModels(); - aborted = countUncommitted + countCommitted + numberOfModels > bound; - if (!aborted) { - countUncommitted += numberOfModels; - } + countUncommitted += numberOfModels; } else if (event == SimpleEvent.MODEL_ENUMERATION_COMMIT) { countCommitted += countUncommitted; countUncommitted = 0; } else if (event == SimpleEvent.MODEL_ENUMERATION_ROLLBACK) { countUncommitted = 0; } - return !aborted; + return countUncommitted + countCommitted < bound; } } diff --git a/src/main/java/com/booleworks/logicng/handlers/NumberOfNodesBDDHandler.java b/src/main/java/com/booleworks/logicng/handlers/NumberOfNodesBDDHandler.java index 7ca71a58..df3807fa 100644 --- a/src/main/java/com/booleworks/logicng/handlers/NumberOfNodesBDDHandler.java +++ b/src/main/java/com/booleworks/logicng/handlers/NumberOfNodesBDDHandler.java @@ -7,7 +7,7 @@ import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.BDD_COMPUTATION_STARTED; import static com.booleworks.logicng.handlers.events.SimpleEvent.BDD_NEW_REF_ADDED; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * A BDD handler which cancels the build process after a given number of added @@ -34,7 +34,7 @@ public NumberOfNodesBDDHandler(final int bound) { } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == BDD_COMPUTATION_STARTED) { count = 0; } else if (event == BDD_NEW_REF_ADDED) { @@ -42,9 +42,4 @@ public boolean shouldResume(final LogicNGEvent event) { } return !aborted; } - - @Override - public boolean isAborted() { - return aborted; - } } diff --git a/src/main/java/com/booleworks/logicng/handlers/SatResult.java b/src/main/java/com/booleworks/logicng/handlers/SatResult.java new file mode 100644 index 00000000..fdf6bf32 --- /dev/null +++ b/src/main/java/com/booleworks/logicng/handlers/SatResult.java @@ -0,0 +1,54 @@ +package com.booleworks.logicng.handlers; + +import java.util.Objects; + +public class SatResult { + private final R result; + private final boolean sat; + + private SatResult(final R result, final boolean sat) { + this.result = result; + this.sat = sat; + } + + public static SatResult sat(final R result) { + return new SatResult<>(result, true); + } + + public static SatResult unsat() { + return new SatResult<>(null, false); + } + + public R getResult() { + return result; + } + + public boolean isSat() { + return sat; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final SatResult satResult = (SatResult) o; + return sat == satResult.sat && Objects.equals(result, satResult.result); + } + + @Override + public int hashCode() { + return Objects.hash(result, sat); + } + + @Override + public String toString() { + return "SatResult{" + + "result=" + result + + ", sat=" + sat + + '}'; + } +} diff --git a/src/main/java/com/booleworks/logicng/handlers/TimeoutHandler.java b/src/main/java/com/booleworks/logicng/handlers/TimeoutHandler.java index 5333b31e..b31de188 100644 --- a/src/main/java/com/booleworks/logicng/handlers/TimeoutHandler.java +++ b/src/main/java/com/booleworks/logicng/handlers/TimeoutHandler.java @@ -5,7 +5,7 @@ package com.booleworks.logicng.handlers; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * A generic timeout handler. @@ -14,7 +14,6 @@ */ public class TimeoutHandler implements ComputationHandler { - protected boolean aborted = false; protected long timeout; protected final TimerType type; protected long designatedEnd; @@ -58,7 +57,7 @@ public TimeoutHandler(final long timeout) { } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event instanceof ComputationStartedEvent) { if (type == TimerType.RESTARTING_TIMEOUT || designatedEnd == 0) { designatedEnd = System.currentTimeMillis() + timeout; @@ -67,19 +66,13 @@ public boolean shouldResume(final LogicNGEvent event) { return !timeLimitExceeded(); } - @Override - public boolean isAborted() { - return timeLimitExceeded(); - } - /** * Tests if the current time exceeds the timeout limit. * @return {@code true} if the current time exceeds the timeout limit, * otherwise {@code false} */ private boolean timeLimitExceeded() { - aborted = designatedEnd > 0 && System.currentTimeMillis() >= designatedEnd; - return aborted; + return designatedEnd > 0 && System.currentTimeMillis() >= designatedEnd; } /** diff --git a/src/main/java/com/booleworks/logicng/handlers/UnsatResult.java b/src/main/java/com/booleworks/logicng/handlers/UnsatResult.java new file mode 100644 index 00000000..33534c9f --- /dev/null +++ b/src/main/java/com/booleworks/logicng/handlers/UnsatResult.java @@ -0,0 +1,54 @@ +package com.booleworks.logicng.handlers; + +import java.util.Objects; + +public class UnsatResult { + private final R result; + private final boolean unsat; + + private UnsatResult(final R result, final boolean unsat) { + this.result = result; + this.unsat = unsat; + } + + public static UnsatResult sat() { + return new UnsatResult<>(null, false); + } + + public static UnsatResult unsat(final R result) { + return new UnsatResult<>(result, true); + } + + public R getResult() { + return result; + } + + public boolean isUnsat() { + return unsat; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final UnsatResult satResult = (UnsatResult) o; + return unsat == satResult.unsat && Objects.equals(result, satResult.result); + } + + @Override + public int hashCode() { + return Objects.hash(result, unsat); + } + + @Override + public String toString() { + return "UnsatResult{" + + "result=" + result + + ", unsat=" + unsat + + '}'; + } +} diff --git a/src/main/java/com/booleworks/logicng/handlers/events/ComputationFinishedEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/ComputationFinishedEvent.java index 1f918594..4ef78fe8 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/ComputationFinishedEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/ComputationFinishedEvent.java @@ -3,7 +3,7 @@ import com.booleworks.logicng.handlers.ComputationHandler; /** - * A class for {@link LogicNGEvent}s which indicate the end of a computation. + * A class for {@link LNGEvent}s which indicate the end of a computation. * By convention, these events are instantiated as {@code static final} fields * s.t. they can be checked in {@link ComputationHandler handlers} by using * referential equality. @@ -12,7 +12,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class ComputationFinishedEvent implements LogicNGEvent { +public class ComputationFinishedEvent implements LNGEvent { public static final ComputationFinishedEvent SAT_CALL_FINISHED = new ComputationFinishedEvent("SAT Call"); public static final ComputationFinishedEvent MAX_SAT_CALL_FINISHED = new ComputationFinishedEvent("MaxSAT Call"); diff --git a/src/main/java/com/booleworks/logicng/handlers/events/ComputationStartedEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/ComputationStartedEvent.java index edf2dc12..4cbaf622 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/ComputationStartedEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/ComputationStartedEvent.java @@ -4,7 +4,7 @@ import com.booleworks.logicng.handlers.TimeoutHandler; /** - * A class for {@link LogicNGEvent}s which indicate the start of a computation. + * A class for {@link LNGEvent}s which indicate the start of a computation. * By convention, these events are instantiated as {@code static final} fields * s.t. they can be checked in {@link ComputationHandler handlers} by using * referential equality. On the other hand, some handlers (like the @@ -15,7 +15,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class ComputationStartedEvent implements LogicNGEvent { +public class ComputationStartedEvent implements LNGEvent { public static final ComputationStartedEvent FACTORIZATION_STARTED = new ComputationStartedEvent("Factorization"); public static final ComputationStartedEvent BDD_COMPUTATION_STARTED = new ComputationStartedEvent("BDD Computation"); diff --git a/src/main/java/com/booleworks/logicng/handlers/events/EnumerationFoundModelsEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/EnumerationFoundModelsEvent.java index 11c675c4..a973e5e4 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/EnumerationFoundModelsEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/EnumerationFoundModelsEvent.java @@ -11,13 +11,13 @@ * @version 3.0.0 * @since 3.0.0 */ -public class EnumerationFoundModelsEvent implements LogicNGEvent { +public class EnumerationFoundModelsEvent implements LNGEvent { private final int numberOfModels; /** * Creates a new event with the given number of models. - * @param numberOfModels the number of models which were found + * @param numberOfModels the number of models which were found */ public EnumerationFoundModelsEvent(final int numberOfModels) { this.numberOfModels = numberOfModels; diff --git a/src/main/java/com/booleworks/logicng/handlers/events/FactorizationCreatedClauseEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/FactorizationCreatedClauseEvent.java index d3c03dec..0dce7957 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/FactorizationCreatedClauseEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/FactorizationCreatedClauseEvent.java @@ -11,7 +11,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class FactorizationCreatedClauseEvent implements LogicNGEvent { +public class FactorizationCreatedClauseEvent implements LNGEvent { private final Formula clause; diff --git a/src/main/java/com/booleworks/logicng/handlers/events/LogicNGEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/LNGEvent.java similarity index 87% rename from src/main/java/com/booleworks/logicng/handlers/events/LogicNGEvent.java rename to src/main/java/com/booleworks/logicng/handlers/events/LNGEvent.java index 2fe9d699..ce8de523 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/LogicNGEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/LNGEvent.java @@ -7,5 +7,5 @@ * @version 3.0.0 * @since 3.0.0 */ -public interface LogicNGEvent { +public interface LNGEvent { } diff --git a/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewLowerBoundEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewLowerBoundEvent.java index e8ae545b..249a8ffa 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewLowerBoundEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewLowerBoundEvent.java @@ -7,12 +7,12 @@ * @version 3.0.0 * @since 3.0.0 */ -public class MaxSatNewLowerBoundEvent implements LogicNGEvent { +public class MaxSatNewLowerBoundEvent implements LNGEvent { private final int bound; /** * Creates a new event with the given lower bound. - * @param bound the new lower bound + * @param bound the new lower bound */ public MaxSatNewLowerBoundEvent(final int bound) { this.bound = bound; diff --git a/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewUpperBoundEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewUpperBoundEvent.java index db25d785..3fd62b02 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewUpperBoundEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/MaxSatNewUpperBoundEvent.java @@ -7,7 +7,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class MaxSatNewUpperBoundEvent implements LogicNGEvent { +public class MaxSatNewUpperBoundEvent implements LNGEvent { private final int bound; /** diff --git a/src/main/java/com/booleworks/logicng/handlers/events/OptimizationFoundBetterBoundEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/OptimizationFoundBetterBoundEvent.java index f8dcb311..b7e3f264 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/OptimizationFoundBetterBoundEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/OptimizationFoundBetterBoundEvent.java @@ -11,7 +11,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class OptimizationFoundBetterBoundEvent implements LogicNGEvent { +public class OptimizationFoundBetterBoundEvent implements LNGEvent { private final Supplier model; diff --git a/src/main/java/com/booleworks/logicng/handlers/events/SimpleEvent.java b/src/main/java/com/booleworks/logicng/handlers/events/SimpleEvent.java index 6bd6820d..7e77d4c9 100644 --- a/src/main/java/com/booleworks/logicng/handlers/events/SimpleEvent.java +++ b/src/main/java/com/booleworks/logicng/handlers/events/SimpleEvent.java @@ -3,7 +3,7 @@ import com.booleworks.logicng.handlers.ComputationHandler; /** - * A class for simple {@link LogicNGEvent} types which can basically be used + * A class for simple {@link LNGEvent} types which can basically be used * as singletons. By convention, simple events are instantiated as * {@code static final} fields s.t. they can be checked in * {@link ComputationHandler handlers} by using referential equality. @@ -12,7 +12,7 @@ * @version 3.0.0 * @since 3.0.0 */ -public class SimpleEvent implements LogicNGEvent { +public class SimpleEvent implements LNGEvent { public static final SimpleEvent NO_EVENT = new SimpleEvent("No event"); public static final SimpleEvent DISTRIBUTION_PERFORMED = new SimpleEvent("Distribution performed"); @@ -21,6 +21,8 @@ public class SimpleEvent implements LogicNGEvent { public static final SimpleEvent SAT_CONFLICT_DETECTED = new SimpleEvent("SAT conflict detected"); public static final SimpleEvent MODEL_ENUMERATION_COMMIT = new SimpleEvent("Model Enumeration Commit"); public static final SimpleEvent MODEL_ENUMERATION_ROLLBACK = new SimpleEvent("Model Enumeration Rollback"); + public static final SimpleEvent SUBSUMPTION_STARTING_UB_TREE_GENERATION = new SimpleEvent("Starting UB Tree generation"); + public static final SimpleEvent SUBSUMPTION_ADDED_NEW_SET = new SimpleEvent("Adding a new set to the UB Tree"); private final String description; diff --git a/src/main/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDFactory.java b/src/main/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDFactory.java index 11007314..ca39659a 100644 --- a/src/main/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDFactory.java +++ b/src/main/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDFactory.java @@ -42,7 +42,9 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.events.SimpleEvent; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDConstruction; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; @@ -73,7 +75,7 @@ private BDDFactory() { * @return the top node of the BDD */ public static BDD build(final FormulaFactory f, final Formula formula) { - return build(f, formula, null, NopHandler.get()); + return build(f, formula, null, NopHandler.get()).getResult(); } /** @@ -91,7 +93,7 @@ public static BDD build(final FormulaFactory f, final Formula formula) { * computation was aborted */ public static BDD build(final FormulaFactory f, final Formula formula, final BDDKernel kernel) { - return build(f, formula, kernel, NopHandler.get()); + return build(f, formula, kernel, NopHandler.get()).getResult(); } /** @@ -114,12 +116,15 @@ public static BDD build(final FormulaFactory f, final Formula formula, final BDD * @return the top node of the BDD or {@link BDDKernel#BDD_ABORT} if the * computation was aborted */ - public static BDD build(final FormulaFactory f, final Formula formula, final BDDKernel kernel, - final ComputationHandler handler) { + public static LNGResult build(final FormulaFactory f, final Formula formula, final BDDKernel kernel, + final ComputationHandler handler) { handler.shouldResume(BDD_COMPUTATION_STARTED); final int varNum = formula.variables(f).size(); final BDDKernel bddKernel = kernel == null ? new BDDKernel(f, varNum, varNum * 30, varNum * 20) : kernel; - return new BDD(buildRec(f, formula, bddKernel, new BDDConstruction(bddKernel), handler), bddKernel); + final int bddIndex = buildRec(f, formula, bddKernel, new BDDConstruction(bddKernel), handler); + return bddIndex == BDDKernel.BDD_ABORT + ? LNGResult.aborted(SimpleEvent.BDD_NEW_REF_ADDED) + : LNGResult.of(new BDD(bddIndex, bddKernel)); } public static BDD build(final Collection literals, final BDDKernel kernel) { @@ -164,8 +169,7 @@ public static BDD build(final Collection literals, final BDDK * was aborted */ private static int buildRec(final FormulaFactory f, final Formula formula, final BDDKernel kernel, - final BDDConstruction construction, - final ComputationHandler handler) { + final BDDConstruction construction, final ComputationHandler handler) { switch (formula.type()) { case FALSE: return BDDKernel.BDD_FALSE; diff --git a/src/main/java/com/booleworks/logicng/knowledgecompilation/dnnf/DnnfFactory.java b/src/main/java/com/booleworks/logicng/knowledgecompilation/dnnf/DnnfFactory.java index b2d058d4..b4342eb9 100644 --- a/src/main/java/com/booleworks/logicng/knowledgecompilation/dnnf/DnnfFactory.java +++ b/src/main/java/com/booleworks/logicng/knowledgecompilation/dnnf/DnnfFactory.java @@ -37,20 +37,20 @@ public Dnnf compile(final FormulaFactory f, final Formula formula) { * Compiles the given formula to a DNNF instance. * @param f the formula factory to generate new formulas * @param formula the formula - * @param handler the DNNF handler + * @param handler the computation handler * @return the compiled DNNF */ public Dnnf compile(final FormulaFactory f, final Formula formula, final ComputationHandler handler) { final SortedSet originalVariables = new TreeSet<>(formula.variables(f)); final Formula cnf = formula.cnf(f); originalVariables.addAll(cnf.variables(f)); - final Formula simplifiedFormula = simplifyFormula(f, cnf); + final Formula simplifiedFormula = simplifyFormula(f, cnf, handler); final DnnfCompiler compiler = new DnnfCompiler(f, simplifiedFormula); final Formula dnnf = compiler.compile(new MinFillDTreeGenerator(), handler); return dnnf == null ? null : new Dnnf(originalVariables, dnnf); } - protected Formula simplifyFormula(final FormulaFactory f, final Formula formula) { + protected Formula simplifyFormula(final FormulaFactory f, final Formula formula, final ComputationHandler handler) { return formula .transform(new BackboneSimplifier(f)) .transform(new CNFSubsumption(f)); diff --git a/src/main/java/com/booleworks/logicng/np/SetCover.java b/src/main/java/com/booleworks/logicng/np/SetCover.java index 96bb3550..4398879b 100644 --- a/src/main/java/com/booleworks/logicng/np/SetCover.java +++ b/src/main/java/com/booleworks/logicng/np/SetCover.java @@ -67,7 +67,7 @@ public static List> compute(final FormulaFactory f, final Collection< for (final Variable setVar : setMap.keySet()) { solver.addSoftFormula(setVar.negate(f), 1); } - if (solver.solve() != MaxSAT.MaxSATResult.OPTIMUM) { + if (solver.solve().getResult() != MaxSAT.MaxSATResult.OPTIMUM) { throw new IllegalStateException("Internal optimization problem was not feasible."); } final ArrayList minimumCover = diff --git a/src/main/java/com/booleworks/logicng/primecomputation/NaivePrimeReduction.java b/src/main/java/com/booleworks/logicng/primecomputation/NaivePrimeReduction.java index f2e86c42..601095e9 100644 --- a/src/main/java/com/booleworks/logicng/primecomputation/NaivePrimeReduction.java +++ b/src/main/java/com/booleworks/logicng/primecomputation/NaivePrimeReduction.java @@ -4,13 +4,11 @@ package com.booleworks.logicng.primecomputation; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; import com.booleworks.logicng.solvers.SATSolver; @@ -57,7 +55,7 @@ public NaivePrimeReduction(final FormulaFactory f, final Formula formula) { * @return a prime implicant */ public SortedSet reduceImplicant(final SortedSet implicant) { - return reduceImplicant(implicant, NopHandler.get()); + return reduceImplicant(implicant, NopHandler.get()).getResult(); } /** @@ -69,21 +67,22 @@ public SortedSet reduceImplicant(final SortedSet implicant) { * @return a prime implicant or null if the computation was aborted by the * handler */ - public SortedSet reduceImplicant(final SortedSet implicant, final ComputationHandler handler) { + public LNGResult> reduceImplicant(final SortedSet implicant, + final ComputationHandler handler) { handler.shouldResume(ComputationStartedEvent.IMPLICATE_REDUCTION_STARTED); final SortedSet primeImplicant = new TreeSet<>(implicant); for (final Literal lit : implicant) { primeImplicant.remove(lit); - final boolean sat = - implicantSolver.satCall().handler(handler).addFormulas(primeImplicant).sat() == Tristate.TRUE; - if (!handler.shouldResume(NO_EVENT)) { - return null; + final LNGResult sat = + implicantSolver.satCall().handler(handler).addFormulas(primeImplicant).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); } - if (sat) { + if (sat.getResult()) { primeImplicant.add(lit); } } - return primeImplicant; + return LNGResult.of(primeImplicant); } /** @@ -95,7 +94,7 @@ public SortedSet reduceImplicant(final SortedSet implicant, fi * @return a prime implicate */ public SortedSet reduceImplicate(final FormulaFactory f, final SortedSet implicate) { - return reduceImplicate(f, implicate, NopHandler.get()); + return reduceImplicate(f, implicate, NopHandler.get()).getResult(); } /** @@ -108,22 +107,21 @@ public SortedSet reduceImplicate(final FormulaFactory f, final SortedSe * @return a prime implicate of null if the computation was aborted by the * handler */ - public SortedSet reduceImplicate(final FormulaFactory f, final SortedSet implicate, - final ComputationHandler handler) { + public LNGResult> reduceImplicate(final FormulaFactory f, final SortedSet implicate, + final ComputationHandler handler) { handler.shouldResume(ComputationStartedEvent.IMPLICATE_REDUCTION_STARTED); final SortedSet primeImplicate = new TreeSet<>(implicate); for (final Literal lit : implicate) { primeImplicate.remove(lit); final List assumptions = FormulaHelper.negateLiterals(f, primeImplicate, ArrayList::new); - final boolean sat = - implicateSolver.satCall().handler(handler).addFormulas(assumptions).sat() == Tristate.TRUE; - if (!handler.shouldResume(NO_EVENT)) { - return null; + final LNGResult sat = implicateSolver.satCall().handler(handler).addFormulas(assumptions).sat(); + if (!sat.isSuccess()) { + return LNGResult.aborted(sat.getAbortionEvent()); } - if (sat) { + if (sat.getResult()) { primeImplicate.add(lit); } } - return primeImplicate; + return LNGResult.of(primeImplicate); } } diff --git a/src/main/java/com/booleworks/logicng/primecomputation/PrimeCompiler.java b/src/main/java/com/booleworks/logicng/primecomputation/PrimeCompiler.java index d0be17c0..3fb48a2b 100644 --- a/src/main/java/com/booleworks/logicng/primecomputation/PrimeCompiler.java +++ b/src/main/java/com/booleworks/logicng/primecomputation/PrimeCompiler.java @@ -4,16 +4,15 @@ package com.booleworks.logicng.primecomputation; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - import com.booleworks.logicng.datastructures.Assignment; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.SatResult; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.OptimizationFunction; @@ -88,7 +87,7 @@ public static PrimeCompiler getWithMaximization() { * @return the prime result */ public PrimeResult compute(final FormulaFactory f, final Formula formula, final PrimeResult.CoverageType type) { - return compute(f, formula, type, NopHandler.get()); + return compute(f, formula, type, NopHandler.get()).getResult(); } /** @@ -107,25 +106,25 @@ public PrimeResult compute(final FormulaFactory f, final Formula formula, final * @return the prime result or null if the computation was aborted by the * handler */ - public PrimeResult compute(final FormulaFactory f, final Formula formula, final PrimeResult.CoverageType type, - final ComputationHandler handler) { + public LNGResult compute(final FormulaFactory f, final Formula formula, + final PrimeResult.CoverageType type, final ComputationHandler handler) { handler.shouldResume(ComputationStartedEvent.PRIME_COMPUTATION_STARTED); final boolean completeImplicants = type == PrimeResult.CoverageType.IMPLICANTS_COMPLETE; final Formula formulaForComputation = completeImplicants ? formula : formula.negate(f); - final Pair>, List>> result = + final LNGResult>, List>>> genericResult = computeGeneric(f, formulaForComputation, handler); - if (result == null || !handler.shouldResume(NO_EVENT)) { - return null; + if (!genericResult.isSuccess()) { + return LNGResult.aborted(genericResult.getAbortionEvent()); } - return new PrimeResult( + final Pair>, List>> result = genericResult.getResult(); + return LNGResult.of(new PrimeResult( completeImplicants ? result.first() : negateAll(f, result.second()), completeImplicants ? result.second() : negateAll(f, result.first()), - type); + type)); } - private Pair>, List>> computeGeneric(final FormulaFactory f, - final Formula formula, - final ComputationHandler handler) { + private LNGResult>, List>>> computeGeneric( + final FormulaFactory f, final Formula formula, final ComputationHandler handler) { final SubstitutionResult sub = createSubstitution(f, formula); final SATSolver hSolver = SATSolver.newSolver(f, SATSolverConfig.builder().cnfMethod(SATSolverConfig.CNFMethod.PG_ON_SOLVER).build()); @@ -137,30 +136,30 @@ private Pair>, List>> computeGeneric( final List> primeImplicants = new ArrayList<>(); final List> primeImplicates = new ArrayList<>(); while (true) { - final Assignment hModel = hSolver.execute(computeWithMaximization - ? OptimizationFunction.builder().handler(handler).literals(sub.newVar2oldLit.keySet()).maximize() - .build() - : OptimizationFunction.builder().handler(handler).literals(sub.newVar2oldLit.keySet()).minimize() - .build()); - if (!handler.shouldResume(NO_EVENT)) { - return null; + final LNGResult> hModelResult = hSolver.execute(computeWithMaximization + ? OptimizationFunction.builder().literals(sub.newVar2oldLit.keySet()).maximize().build() + : OptimizationFunction.builder().literals(sub.newVar2oldLit.keySet()).minimize().build(), handler); + if (!hModelResult.isSuccess()) { + return LNGResult.aborted(hModelResult.getAbortionEvent()); } - if (hModel == null) { - return new Pair<>(primeImplicants, primeImplicates); + final SatResult hModel = hModelResult.getResult(); + if (!hModel.isSat()) { + return LNGResult.of(new Pair<>(primeImplicants, primeImplicates)); } - final Assignment fModel = transformModel(hModel, sub.newVar2oldLit); + final Assignment fModel = transformModel(hModel.getResult(), sub.newVar2oldLit); try (final SATCall fCall = fSolver.satCall().handler(handler) .addFormulas(fModel.literals()).solve()) { - if (!handler.shouldResume(NO_EVENT)) { - return null; + if (!fCall.getSatResult().isSuccess()) { + return LNGResult.aborted(fCall.getSatResult().getAbortionEvent()); } - if (fCall.getSatResult() == Tristate.FALSE) { - final SortedSet primeImplicant = computeWithMaximization + if (!fCall.getSatResult().getResult()) { + final LNGResult> primeImplicantResult = computeWithMaximization ? primeReduction.reduceImplicant(fModel.literals(), handler) - : fModel.literals(); - if (primeImplicant == null || !handler.shouldResume(NO_EVENT)) { - return null; + : LNGResult.of(fModel.literals()); + if (!primeImplicantResult.isSuccess()) { + return LNGResult.aborted(primeImplicantResult.getAbortionEvent()); } + final SortedSet primeImplicant = primeImplicantResult.getResult(); primeImplicants.add(primeImplicant); final List blockingClause = new ArrayList<>(); for (final Literal lit : primeImplicant) { @@ -169,15 +168,16 @@ private Pair>, List>> computeGeneric( hSolver.add(f.or(blockingClause)); } else { final SortedSet implicate = new TreeSet<>(); - for (final Literal lit : (computeWithMaximization ? fModel : fCall.model(formula.variables(f))) - .literals()) { + for (final Literal lit : + (computeWithMaximization ? fModel : fCall.model(formula.variables(f))).literals()) { implicate.add(lit.negate(f)); } - final SortedSet primeImplicate = + final LNGResult> primeImplicateResult = primeReduction.reduceImplicate(f, implicate, handler); - if (primeImplicate == null || !handler.shouldResume(NO_EVENT)) { - return null; + if (!primeImplicateResult.isSuccess()) { + return LNGResult.aborted(primeImplicateResult.getAbortionEvent()); } + final SortedSet primeImplicate = primeImplicateResult.getResult(); primeImplicates.add(primeImplicate); hSolver.add(f.or(primeImplicate).transform(sub.substitution)); } diff --git a/src/main/java/com/booleworks/logicng/solvers/MaxSATSolver.java b/src/main/java/com/booleworks/logicng/solvers/MaxSATSolver.java index 9901cb41..6b55c21f 100644 --- a/src/main/java/com/booleworks/logicng/solvers/MaxSATSolver.java +++ b/src/main/java/com/booleworks/logicng/solvers/MaxSATSolver.java @@ -5,7 +5,6 @@ package com.booleworks.logicng.solvers; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT.MaxSATResult.OPTIMUM; -import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT.MaxSATResult.UNDEF; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT.MaxSATResult.UNSATISFIABLE; import com.booleworks.logicng.collections.LNGBooleanVector; @@ -17,6 +16,7 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.solvers.maxsat.algorithms.IncWBO; import com.booleworks.logicng.solvers.maxsat.algorithms.LinearSU; @@ -55,7 +55,7 @@ protected enum Algorithm { protected final MaxSATConfig configuration; protected final Algorithm algorithm; protected FormulaFactory f; - protected MaxSAT.MaxSATResult result; + protected LNGResult result; protected MaxSAT solver; protected SortedMap var2index; protected SortedMap index2var; @@ -242,7 +242,7 @@ public boolean isWeighted() { * @throws IllegalArgumentException if the algorithm was unknown */ public void reset() { - result = UNDEF; + result = null; var2index = new TreeMap<>(); index2var = new TreeMap<>(); selectorVariables = new TreeSet<>(); @@ -280,7 +280,7 @@ public void reset() { * already solved. */ public void addHardFormula(final Formula formula) { - if (result != UNDEF) { + if (result != null) { throw new IllegalStateException( "The MaxSAT solver does currently not support an incremental interface. Reset the solver."); } @@ -296,7 +296,7 @@ public void addHardFormula(final Formula formula) { * @throws IllegalArgumentException if the weight is <1 */ public void addSoftFormula(final Formula formula, final int weight) { - if (result != UNDEF) { + if (result != null) { throw new IllegalStateException( "The MaxSAT solver does currently not support an incremental interface. Reset the solver."); } @@ -340,7 +340,7 @@ protected void addCNF(final Formula formula, final int weight) { * @param weight the weight of the clause (or -1 for a hard clause) */ protected void addClause(final Formula formula, final int weight) { - result = UNDEF; + result = null; final LNGIntVector clauseVec = new LNGIntVector((int) formula.numberOfAtoms(f)); for (final Literal lit : formula.literals(f)) { Integer index = var2index.get(lit.variable()); @@ -365,7 +365,7 @@ protected void addClause(final Formula formula, final int weight) { * Solves the formula on the solver and returns the result. * @return the result (SAT, UNSAT, Optimum found) */ - public MaxSAT.MaxSATResult solve() { + public LNGResult solve() { return solve(NopHandler.get()); } @@ -375,8 +375,8 @@ public MaxSAT.MaxSATResult solve() { * @return the result (SAT, UNSAT, Optimum found, or UNDEF if canceled by * the handler) */ - public MaxSAT.MaxSATResult solve(final ComputationHandler handler) { - if (result != UNDEF) { + public LNGResult solve(final ComputationHandler handler) { + if (result != null && result.isSuccess()) { return result; } if (solver.currentWeight() == 1) { @@ -396,11 +396,11 @@ public MaxSAT.MaxSATResult solve(final ComputationHandler handler) { * @throws IllegalStateException if the formula is not yet solved */ public int result() { - if (result == UNDEF) { + if (result == null || !result.isSuccess()) { throw new IllegalStateException( "Cannot get a result as long as the formula is not solved. Call 'solver' first."); } - return result == OPTIMUM ? solver.result() : -1; + return result.getResult() == OPTIMUM ? solver.result() : -1; } /** @@ -409,11 +409,11 @@ public int result() { * @throws IllegalStateException if the formula is not yet solved */ public Assignment model() { - if (result == UNDEF) { + if (result == null || !result.isSuccess()) { throw new IllegalStateException( "Cannot get a model as long as the formula is not solved. Call 'solver' first."); } - return result != UNSATISFIABLE ? createAssignment(solver.model()) : null; + return result.getResult() != UNSATISFIABLE ? createAssignment(solver.model()) : null; } /** diff --git a/src/main/java/com/booleworks/logicng/solvers/SATSolver.java b/src/main/java/com/booleworks/logicng/solvers/SATSolver.java index dee9663e..a156947a 100644 --- a/src/main/java/com/booleworks/logicng/solvers/SATSolver.java +++ b/src/main/java/com/booleworks/logicng/solvers/SATSolver.java @@ -10,7 +10,6 @@ import com.booleworks.logicng.configurations.ConfigurationType; import com.booleworks.logicng.datastructures.EncodingResult; import com.booleworks.logicng.datastructures.Model; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.encodings.CcEncoder; import com.booleworks.logicng.encodings.CcIncrementalData; import com.booleworks.logicng.encodings.PbEncoder; @@ -21,6 +20,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.PBConstraint; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.solvers.functions.BackboneFunction; import com.booleworks.logicng.solvers.functions.ModelEnumerationFunction; @@ -294,7 +295,7 @@ public SATCallBuilder satCall() { */ public boolean sat() { try (final SATCall call = satCall().solve()) { - return call.getSatResult() == Tristate.TRUE; + return call.getSatResult().getResult(); } } @@ -311,6 +312,21 @@ public RESULT execute(final SolverFunction function) { return function.apply(this); } + /** + * Executes a solver function on this solver. + * @param function the solver function + * @param handler the computation handler + * @param the result type of the function + * @return the (potentially aborted) result of executing the solver + * function on the current solver + * @throws IllegalStateException if this solver is currently used in a + * {@link SATCall} + */ + public LNGResult execute(final SolverFunction function, final ComputationHandler handler) { + solver.assertNotInSatCall(); + return function.apply(this, handler); + } + /** * Enumerates all models of the current formula wrt. a given set of * variables. If the set is {@code null}, all variables are considered diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/BackboneFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/BackboneFunction.java index 3f2c4001..27805a20 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/BackboneFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/BackboneFunction.java @@ -10,6 +10,7 @@ import com.booleworks.logicng.backbones.BackboneType; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.SolverState; @@ -26,12 +27,10 @@ */ public final class BackboneFunction implements SolverFunction { - private final ComputationHandler handler; private final Collection variables; private final BackboneType type; - private BackboneFunction(final ComputationHandler handler, final Collection variables, final BackboneType type) { - this.handler = handler; + private BackboneFunction(final Collection variables, final BackboneType type) { this.variables = variables; this.type = type; } @@ -45,12 +44,8 @@ public static Builder builder() { } @Override - public Backbone apply(final SATSolver solver) { - handler.shouldResume(BACKBONE_COMPUTATION_STARTED); - final SolverState stateBeforeBackbone = solver.saveState(); - final Backbone backbone = solver.underlyingSolver().computeBackbone(variables, type, handler); - solver.loadState(stateBeforeBackbone); - return backbone; + public LNGResult apply(final SATSolver solver, ComputationHandler handler) { + return solver.underlyingSolver().computeBackbone(variables, type, handler); } /** @@ -58,7 +53,6 @@ public Backbone apply(final SATSolver solver) { */ public static class Builder { - private ComputationHandler handler = NopHandler.get(); private Collection variables; private BackboneType type = BackboneType.POSITIVE_AND_NEGATIVE; @@ -66,16 +60,6 @@ private Builder() { // Initialize only via factory } - /** - * Sets the SAT handler for this function. - * @param handler the handler - * @return the current builder - */ - public Builder handler(final ComputationHandler handler) { - this.handler = handler; - return this; - } - /** * Sets the variables which are relevant for the backbone computation. * @param variables the variables @@ -113,7 +97,7 @@ public Builder type(final BackboneType type) { * @return the backbone function */ public BackboneFunction build() { - return new BackboneFunction(handler, variables, type); + return new BackboneFunction(variables, type); } } } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/FormulaOnSolverFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/FormulaOnSolverFunction.java index e38acbe3..4bb47669 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/FormulaOnSolverFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/FormulaOnSolverFunction.java @@ -13,6 +13,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.datastructures.LNGClause; import com.booleworks.logicng.solvers.datastructures.LNGVariable; @@ -61,7 +63,7 @@ public static FormulaOnSolverFunction get() { } @Override - public Set apply(final SATSolver solver) { + public LNGResult> apply(final SATSolver solver, final ComputationHandler handler) { final FormulaFactory f = solver.factory(); final Set formulas = new LinkedHashSet<>(); for (final LNGClause clause : solver.underlyingSolver().clauses()) { @@ -91,6 +93,6 @@ public Set apply(final SATSolver solver) { if (!solver.underlyingSolver().ok()) { formulas.add(f.falsum()); } - return formulas; + return LNGResult.of(formulas); } } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/ModelCountingFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/ModelCountingFunction.java index 625b943b..ab65be5c 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/ModelCountingFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/ModelCountingFunction.java @@ -15,6 +15,7 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; import com.booleworks.logicng.handlers.events.EnumerationFoundModelsEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.modelenumeration.AbstractModelEnumerationFunction; import com.booleworks.logicng.solvers.functions.modelenumeration.EnumerationCollector; @@ -116,28 +117,25 @@ public ModelCountCollector(final int numberDontCareVariablesNotOnSolver) { } @Override - public boolean addModel(final LNGBooleanVector modelFromSolver, final SATSolver solver, - final LNGIntVector relevantAllIndices, final ComputationHandler handler) { - if (handler.shouldResume(new EnumerationFoundModelsEvent(dontCareFactor.intValue()))) { - uncommittedModels.add(modelFromSolver); - uncommittedIndices.add(relevantAllIndices); - return true; - } else { - return false; - } + public LNGEvent addModel(final LNGBooleanVector modelFromSolver, final SATSolver solver, + final LNGIntVector relevantAllIndices, final ComputationHandler handler) { + final EnumerationFoundModelsEvent event = new EnumerationFoundModelsEvent(dontCareFactor.intValue()); + uncommittedModels.add(modelFromSolver); + uncommittedIndices.add(relevantAllIndices); + return handler.shouldResume(event) ? null : event; } @Override - public boolean commit(final ComputationHandler handler) { + public LNGEvent commit(final ComputationHandler handler) { committedCount = committedCount.add(BigInteger.valueOf(uncommittedModels.size()).multiply(dontCareFactor)); clearUncommitted(); - return handler.shouldResume(MODEL_ENUMERATION_COMMIT); + return handler.shouldResume(MODEL_ENUMERATION_COMMIT) ? null : MODEL_ENUMERATION_COMMIT; } @Override - public boolean rollback(final ComputationHandler handler) { + public LNGEvent rollback(final ComputationHandler handler) { clearUncommitted(); - return handler.shouldResume(MODEL_ENUMERATION_ROLLBACK); + return handler.shouldResume(MODEL_ENUMERATION_ROLLBACK) ? null : MODEL_ENUMERATION_ROLLBACK; } @Override diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunction.java index f4afbb62..89bc5e33 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunction.java @@ -18,6 +18,7 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; import com.booleworks.logicng.handlers.events.EnumerationFoundModelsEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.modelenumeration.AbstractModelEnumerationFunction; import com.booleworks.logicng.solvers.functions.modelenumeration.EnumerationCollector; @@ -148,32 +149,28 @@ public ModelEnumerationCollector(final FormulaFactory f, final SortedSet modelLiterals = new ArrayList<>(additionalVariablesNotOnSolver); - modelLiterals.addAll(model.getLiterals()); - uncommittedModels.add(modelLiterals); - return true; - } else { - return false; - } + public LNGEvent addModel(final LNGBooleanVector modelFromSolver, final SATSolver solver, + final LNGIntVector relevantAllIndices, final ComputationHandler handler) { + final Model model = + new Model(solver.underlyingSolver().convertInternalModel(modelFromSolver, relevantAllIndices)); + final List modelLiterals = new ArrayList<>(additionalVariablesNotOnSolver); + modelLiterals.addAll(model.getLiterals()); + uncommittedModels.add(modelLiterals); + final EnumerationFoundModelsEvent event = new EnumerationFoundModelsEvent(baseModels.size()); + return handler.shouldResume(event) ? null : event; } @Override - public boolean commit(final ComputationHandler handler) { + public LNGEvent commit(final ComputationHandler handler) { committedModels.addAll(expandUncommittedModels()); uncommittedModels.clear(); - return handler.shouldResume(MODEL_ENUMERATION_COMMIT); + return !handler.shouldResume(MODEL_ENUMERATION_COMMIT) ? MODEL_ENUMERATION_COMMIT : null; } @Override - public boolean rollback(final ComputationHandler handler) { + public LNGEvent rollback(final ComputationHandler handler) { uncommittedModels.clear(); - return handler.shouldResume(MODEL_ENUMERATION_ROLLBACK); + return !handler.shouldResume(MODEL_ENUMERATION_ROLLBACK) ? MODEL_ENUMERATION_ROLLBACK : null; } @Override diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunction.java index 599e3ae7..3a5fc05a 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunction.java @@ -16,6 +16,7 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; import com.booleworks.logicng.handlers.events.EnumerationFoundModelsEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.knowledgecompilation.bdds.BDD; import com.booleworks.logicng.knowledgecompilation.bdds.BDDFactory; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; @@ -129,26 +130,23 @@ public BddModelEnumerationCollector(final FormulaFactory f, final SortedSet { +public final class OptimizationFunction implements SolverFunction> { private static final String SEL_PREFIX = "@SEL_OPT_"; private final Collection literals; private final SortedSet resultModelVariables; private final boolean maximize; - private final ComputationHandler handler; private OptimizationFunction(final Collection literals, - final Collection additionalVariables, final boolean maximize, - final ComputationHandler handler) { + final Collection additionalVariables, final boolean maximize) { this.literals = literals; resultModelVariables = new TreeSet<>(additionalVariables); for (final Literal lit : literals) { resultModelVariables.add(lit.variable()); } this.maximize = maximize; - this.handler = handler; } /** @@ -91,15 +88,19 @@ public static OptimizationFunction minimize(final Collection } @Override - public Assignment apply(final SATSolver solver) { + public LNGResultWithPartial, SatResult> apply( + final SATSolver solver, final ComputationHandler handler) { final SolverState initialState = solver.saveState(); - final Assignment model = maximize(solver); + final LNGResultWithPartial, SatResult> model = maximize(solver, handler); solver.loadState(initialState); return model; } - private Assignment maximize(final SATSolver solver) { - handler.shouldResume(ComputationStartedEvent.OPTIMIZATION_FUNCTION_STARTED); + private LNGResultWithPartial, SatResult> maximize( + final SATSolver solver, final ComputationHandler handler) { + if (!handler.shouldResume(OPTIMIZATION_FUNCTION_STARTED)) { + return LNGResultWithPartial.aborted(null, OPTIMIZATION_FUNCTION_STARTED); + } final FormulaFactory f = solver.factory(); final Map selectorMap = new TreeMap<>(); for (final Literal lit : literals) { @@ -117,26 +118,29 @@ private Assignment maximize(final SATSolver solver) { Assignment lastResultModel; Assignment currentSelectorModel; try (final SATCall satCall = solver.satCall().handler(handler).solve()) { - if (satCall.getSatResult() != Tristate.TRUE || !handler.shouldResume(NO_EVENT)) { - return null; + if (!satCall.getSatResult().isSuccess()) { + return LNGResultWithPartial.aborted(null, satCall.getSatResult().getAbortionEvent()); + } + if (!satCall.getSatResult().getResult()) { + return LNGResultWithPartial.ofResult(SatResult.unsat()); } lastResultModel = satCall.model(resultModelVariables); currentSelectorModel = satCall.model(selectors); if (currentSelectorModel.positiveVariables().size() == selectors.size()) { // all optimization literals satisfied -- no need for further // optimization - return satCall.model(resultModelVariables); + return LNGResultWithPartial.ofResult(SatResult.sat(satCall.model(resultModelVariables))); } } int currentBound = currentSelectorModel.positiveVariables().size(); if (currentBound == 0) { solver.add(f.cc(CType.GE, 1, selectors)); try (final SATCall satCall = solver.satCall().handler(handler).solve()) { - final Tristate sat = satCall.getSatResult(); - if (!handler.shouldResume(NO_EVENT)) { - return null; - } else if (sat == Tristate.FALSE) { - return lastResultModel; + final LNGResult satResult = satCall.getSatResult(); + if (!satResult.isSuccess()) { + return LNGResultWithPartial.aborted(SatResult.sat(lastResultModel), satResult.getAbortionEvent()); + } else if (!satResult.getResult()) { + return LNGResultWithPartial.ofResult(SatResult.sat(lastResultModel)); } else { lastResultModel = satCall.model(resultModelVariables); currentSelectorModel = satCall.model(selectors); @@ -149,20 +153,21 @@ private Assignment maximize(final SATSolver solver) { final CcIncrementalData incrementalData = solver.addIncrementalCc((CardinalityConstraint) cc); while (true) { try (final SATCall satCall = solver.satCall().handler(handler).solve()) { - if (!handler.shouldResume(NO_EVENT)) { - return null; - } - if (satCall.getSatResult() == Tristate.FALSE) { - return lastResultModel; - } - if (!handler.shouldResume(new OptimizationFoundBetterBoundEvent(() -> satCall.model(resultModelVariables)))) { - return null; + final LNGResult satResult = satCall.getSatResult(); + if (!satResult.isSuccess()) { + return LNGResultWithPartial.aborted(SatResult.sat(lastResultModel), satResult.getAbortionEvent()); + } else if (!satResult.getResult()) { + return LNGResultWithPartial.ofResult(SatResult.sat(lastResultModel)); } lastResultModel = satCall.model(resultModelVariables); + final OptimizationFoundBetterBoundEvent betterBoundEvent = new OptimizationFoundBetterBoundEvent(() -> satCall.model(resultModelVariables)); + if (!handler.shouldResume(betterBoundEvent)) { + return LNGResultWithPartial.aborted(SatResult.sat(lastResultModel), betterBoundEvent); + } currentSelectorModel = satCall.model(selectors); currentBound = currentSelectorModel.positiveVariables().size(); if (currentBound == selectors.size()) { - return lastResultModel; + return LNGResultWithPartial.ofResult(SatResult.sat(lastResultModel)); } } incrementalData.newLowerBoundForSolver(currentBound + 1); @@ -176,7 +181,6 @@ public static class Builder { private Collection literals; private Collection additionalVariables = new TreeSet<>(); private boolean maximize = true; - private ComputationHandler handler = NopHandler.get(); private Builder() { // Initialize only via factory @@ -244,23 +248,13 @@ public Builder maximize() { return this; } - /** - * Sets the handler for the optimization. - * @param handler the handler - * @return the current builder - */ - public Builder handler(final ComputationHandler handler) { - this.handler = handler; - return this; - } - /** * Builds the optimization function with the current builder's * configuration. * @return the optimization function */ public OptimizationFunction build() { - return new OptimizationFunction(literals, additionalVariables, maximize, handler); + return new OptimizationFunction(literals, additionalVariables, maximize); } } } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/SolverFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/SolverFunction.java index 3a5ad7ea..a5b00288 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/SolverFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/SolverFunction.java @@ -4,6 +4,9 @@ package com.booleworks.logicng.solvers.functions; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.solvers.SATSolver; /** @@ -17,10 +20,20 @@ */ public interface SolverFunction { + /** + * Applies this function to the given solver. + * @param solver the solver on which the function should work on + * @param handler the computation handler + * @return the (potentially aborted) result of the function application + */ + LNGResult apply(SATSolver solver, ComputationHandler handler); + /** * Applies this function to the given solver. * @param solver the solver on which the function should work on * @return the result of the function application */ - RESULT apply(SATSolver solver); + default RESULT apply(final SATSolver solver) { + return apply(solver, NopHandler.get()).getResult(); + } } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/UnsatCoreFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/UnsatCoreFunction.java index cf3c8080..3c6b5e9f 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/UnsatCoreFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/UnsatCoreFunction.java @@ -10,6 +10,8 @@ import com.booleworks.logicng.explanations.drup.DRUPTrim; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.propositions.StandardProposition; import com.booleworks.logicng.solvers.SATSolver; @@ -47,7 +49,7 @@ public static UnsatCoreFunction get() { } @Override - public UNSATCore apply(final SATSolver solver) { + public LNGResult> apply(final SATSolver solver, ComputationHandler handler) { if (!solver.config().proofGeneration()) { throw new IllegalStateException("Cannot generate an unsat core if proof generation is not turned on"); } @@ -67,18 +69,18 @@ public UNSATCore apply(final SATSolver solver) { if (containsEmptyClause(clauses)) { final Proposition emptyClause = clause2proposition.get(solver.factory().falsum()); - return new UNSATCore<>(Collections.singletonList(emptyClause), true); + return LNGResult.of(new UNSATCore<>(Collections.singletonList(emptyClause), true)); } final DRUPTrim.DRUPResult result = trimmer.compute(clauses, solver.underlyingSolver().pgProof()); if (result.trivialUnsat()) { - return handleTrivialCase(solver); + return LNGResult.of(handleTrivialCase(solver)); } final LinkedHashSet propositions = new LinkedHashSet<>(); for (final LNGIntVector vector : result.unsatCore()) { propositions.add(clause2proposition.get(getFormulaForVector(solver, vector))); } - return new UNSATCore<>(new ArrayList<>(propositions), false); + return LNGResult.of(new UNSATCore<>(new ArrayList<>(propositions), false)); } private UNSATCore handleTrivialCase(final SATSolver solver) { diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/UpZeroLiteralsFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/UpZeroLiteralsFunction.java index b4c4660f..52c02647 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/UpZeroLiteralsFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/UpZeroLiteralsFunction.java @@ -6,6 +6,9 @@ import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.SatResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -19,7 +22,7 @@ * @version 2.0.0 * @since 2.0.0 */ -public final class UpZeroLiteralsFunction implements SolverFunction> { +public final class UpZeroLiteralsFunction implements SolverFunction>> { private final static UpZeroLiteralsFunction INSTANCE = new UpZeroLiteralsFunction(); @@ -39,9 +42,9 @@ public static UpZeroLiteralsFunction get() { } @Override - public SortedSet apply(final SATSolver solver) { + public LNGResult>> apply(final SATSolver solver, final ComputationHandler handler) { if (!solver.sat()) { - return null; + return LNGResult.of(SatResult.unsat()); } final LNGIntVector literals = solver.underlyingSolver().upZeroLiterals(); final SortedSet upZeroLiterals = new TreeSet<>(); @@ -50,6 +53,6 @@ public SortedSet apply(final SATSolver solver) { upZeroLiterals.add(solver.factory().literal(solver.underlyingSolver().nameForIdx(LNGCoreSolver.var(lit)), !LNGCoreSolver.sign(lit))); } - return upZeroLiterals; + return LNGResult.of(SatResult.sat(upZeroLiterals)); } } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/VariableOccurrencesOnSolverFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/VariableOccurrencesOnSolverFunction.java index 3e45091d..9346743e 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/VariableOccurrencesOnSolverFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/VariableOccurrencesOnSolverFunction.java @@ -10,6 +10,8 @@ import com.booleworks.logicng.collections.LNGVector; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.datastructures.LNGClause; import com.booleworks.logicng.solvers.datastructures.LNGVariable; @@ -56,7 +58,7 @@ public VariableOccurrencesOnSolverFunction(final Set relevantVariables } @Override - public Map apply(final SATSolver solver) { + public LNGResult> apply(final SATSolver solver, final ComputationHandler handler) { final FormulaFactory f = solver.factory(); final LNGCoreSolver underlyingSolver = solver.underlyingSolver(); final Map counts = initResultMap(underlyingSolver); @@ -66,7 +68,8 @@ public Map apply(final SATSolver solver) { counts.computeIfPresent(key, (u, old) -> old + 1); } } - return counts.entrySet().stream().collect(Collectors.toMap(v -> f.variable(v.getKey()), Map.Entry::getValue)); + return LNGResult.of(counts.entrySet().stream() + .collect(Collectors.toMap(v -> f.variable(v.getKey()), Map.Entry::getValue))); } private Map initResultMap(final LNGCoreSolver underlyingSolver) { diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/AbstractModelEnumerationFunction.java b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/AbstractModelEnumerationFunction.java index 415f3799..e1f39556 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/AbstractModelEnumerationFunction.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/AbstractModelEnumerationFunction.java @@ -4,8 +4,7 @@ package com.booleworks.logicng.solvers.functions.modelenumeration; -import static com.booleworks.logicng.datastructures.Tristate.TRUE; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; +import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.MODEL_ENUMERATION_STARTED; import static com.booleworks.logicng.solvers.functions.modelenumeration.ModelEnumerationCommon.generateBlockingClause; import static com.booleworks.logicng.solvers.functions.modelenumeration.ModelEnumerationCommon.relevantAllIndicesFromSolver; import static com.booleworks.logicng.solvers.functions.modelenumeration.ModelEnumerationCommon.relevantIndicesFromSolver; @@ -20,7 +19,9 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.events.ComputationStartedEvent; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.SolverState; import com.booleworks.logicng.solvers.functions.SolverFunction; @@ -41,7 +42,6 @@ public abstract class AbstractModelEnumerationFunction implements Solver protected final SortedSet variables; protected final SortedSet additionalVariables; - protected final ComputationHandler handler; protected final ModelEnumerationStrategy strategy; protected AbstractModelEnumerationFunction(final SortedSet variables, @@ -49,7 +49,6 @@ protected AbstractModelEnumerationFunction(final SortedSet variables, final ModelEnumerationConfig configuration) { this.variables = variables; this.additionalVariables = additionalVariables; - handler = configuration.handler; strategy = configuration.strategy == null ? NoSplitModelEnumerationStrategy.get() : configuration.strategy; } @@ -59,8 +58,10 @@ protected abstract EnumerationCollector newCollector(final FormulaFactor SortedSet additionalVariablesNotOnSolver); @Override - public RESULT apply(final SATSolver solver) { - handler.shouldResume(ComputationStartedEvent.MODEL_ENUMERATION_STARTED); + public LNGResultWithPartial apply(final SATSolver solver, final ComputationHandler handler) { + if (!handler.shouldResume(MODEL_ENUMERATION_STARTED)) { + return LNGResultWithPartial.aborted(null, MODEL_ENUMERATION_STARTED); + } final SortedSet knownVariables = solver.underlyingSolver().knownVariables(); final SortedSet additionalVarsNotOnSolver = difference(additionalVariables, knownVariables, TreeSet::new); @@ -71,36 +72,53 @@ public RESULT apply(final SATSolver solver) { knownVariables.stream().filter(variables::contains).collect(Collectors.toCollection(TreeSet::new)); final SortedSet initialSplitVars = nullSafe(() -> strategy.splitVarsForRecursionDepth(enumerationVars, solver, 0), TreeSet::new); - enumerateRecursive(collector, solver, new TreeSet<>(), enumerationVars, initialSplitVars, 0); - return collector.getResult(); + final LNGEvent abortionEvent = enumerateRecursive(collector, solver, new TreeSet<>(), enumerationVars, initialSplitVars, 0, handler); + final RESULT result = collector.getResult(); + if (abortionEvent == null) { + return LNGResultWithPartial.ofResult(result); + } else { + return LNGResultWithPartial.aborted(result, abortionEvent); + } } - private void enumerateRecursive(final EnumerationCollector collector, final SATSolver solver, - final SortedSet splitModel, final SortedSet enumerationVars, - final SortedSet splitVars, final int recursionDepth) { + private LNGEvent enumerateRecursive(final EnumerationCollector collector, final SATSolver solver, + final SortedSet splitModel, final SortedSet enumerationVars, + final SortedSet splitVars, final int recursionDepth, final ComputationHandler handler) { final int maxNumberOfModelsForEnumeration = strategy.maxNumberOfModelsForEnumeration(recursionDepth); final SolverState state = solver.saveState(); solver.add(splitModel); - final boolean enumerationFinished = enumerate(collector, solver, enumerationVars, + final LNGResult enumerationSucceeded = enumerate(collector, solver, enumerationVars, additionalVariables, maxNumberOfModelsForEnumeration, handler); - if (!enumerationFinished) { - if (!collector.rollback(handler)) { + if (!enumerationSucceeded.isSuccess()) { + collector.commit(handler); + return enumerationSucceeded.getAbortionEvent(); + } + if (!enumerationSucceeded.getResult()) { + final LNGEvent abortionEvent = collector.rollback(handler); + if (abortionEvent != null) { solver.loadState(state); - return; + return abortionEvent; } SortedSet newSplitVars = new TreeSet<>(splitVars); final int maxNumberOfModelsForSplitAssignments = strategy.maxNumberOfModelsForSplitAssignments(recursionDepth); - while (!enumerate(collector, solver, newSplitVars, null, maxNumberOfModelsForSplitAssignments, handler)) { - if (!collector.rollback(handler)) { + while (true) { + final LNGResult enumerationForSplit = enumerate( + collector, solver, newSplitVars, null, maxNumberOfModelsForSplitAssignments, handler); + if (!enumerationForSplit.isSuccess()) { solver.loadState(state); - return; + collector.rollback(handler); + return enumerationForSplit.getAbortionEvent(); + } else if (enumerationForSplit.getResult()) { + break; + } else { + final LNGEvent abortionOnRollback = collector.rollback(handler); + if (abortionOnRollback != null) { + solver.loadState(state); + return abortionOnRollback; + } + newSplitVars = strategy.reduceSplitVars(newSplitVars, recursionDepth); } - newSplitVars = strategy.reduceSplitVars(newSplitVars, recursionDepth); - } - if (!handler.shouldResume(NO_EVENT)) { - collector.rollback(handler); - return; } final SortedSet remainingVars = new TreeSet<>(enumerationVars); @@ -116,40 +134,43 @@ private void enumerateRecursive(final EnumerationCollector collector, fi final SortedSet recursiveSplitModel = new TreeSet<>(newSplitAssignment.getLiterals()); recursiveSplitModel.addAll(splitModel); enumerateRecursive(collector, solver, recursiveSplitModel, enumerationVars, recursiveSplitVars, - recursionDepth + 1); - if (!collector.commit(handler)) { + recursionDepth + 1, handler); + final LNGEvent commitEvent = collector.commit(handler); + if (commitEvent != null) { solver.loadState(state); - return; + return commitEvent; } } } else { - if (!collector.commit(handler)) { + final LNGEvent commitEvent = collector.commit(handler); + if (commitEvent != null) { solver.loadState(state); - return; + return commitEvent; } } solver.loadState(state); + return null; } - protected static boolean enumerate(final EnumerationCollector collector, final SATSolver solver, - final SortedSet variables, - final SortedSet additionalVariables, final int maxModels, - final ComputationHandler handler) { + protected static LNGResult enumerate(final EnumerationCollector collector, final SATSolver solver, + final SortedSet variables, + final SortedSet additionalVariables, final int maxModels, + final ComputationHandler handler) { final SolverState stateBeforeEnumeration = solver.saveState(); final LNGIntVector relevantIndices = relevantIndicesFromSolver(variables, solver); final LNGIntVector relevantAllIndices = relevantAllIndicesFromSolver(variables, additionalVariables, relevantIndices, solver); int foundModels = 0; - boolean proceed = true; - while (proceed && modelEnumerationSATCall(solver, handler)) { + LNGEvent abortionEvent = null; + while (modelEnumerationSATCall(solver, handler)) { final LNGBooleanVector modelFromSolver = solver.underlyingSolver().model(); if (++foundModels >= maxModels) { solver.loadState(stateBeforeEnumeration); - return false; + return LNGResult.of(false); } - proceed = collector.addModel(modelFromSolver, solver, relevantAllIndices, handler); - if (modelFromSolver.size() > 0) { + abortionEvent = collector.addModel(modelFromSolver, solver, relevantAllIndices, handler); + if (abortionEvent == null && modelFromSolver.size() > 0) { final LNGIntVector blockingClause = generateBlockingClause(modelFromSolver, relevantIndices); solver.underlyingSolver().addClause(blockingClause, null); } else { @@ -157,12 +178,12 @@ protected static boolean enumerate(final EnumerationCollector collector, } } solver.loadState(stateBeforeEnumeration); - return true; + return abortionEvent == null ? LNGResult.of(true) : LNGResult.aborted(abortionEvent); } private static boolean modelEnumerationSATCall(final SATSolver solver, final ComputationHandler handler) { - final boolean sat = solver.satCall().handler(handler).sat() == TRUE; - return handler.shouldResume(NO_EVENT) && sat; + final LNGResult sat = solver.satCall().handler(handler).sat(); + return sat.isSuccess() && sat.getResult(); } protected static FormulaFactory factory(final SortedSet variables) { diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollector.java b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollector.java index 4c562164..01f67098 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollector.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollector.java @@ -8,6 +8,7 @@ import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.datastructures.Model; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.SATSolver; import java.util.List; @@ -35,44 +36,47 @@ public interface EnumerationCollector { * @param solver the solver * @param relevantAllIndices the relevant indices * @param handler the model enumeration handler - * @return true if adding the model was successful, false otherwise + * @return an event if the handler aborted the computation, + * otherwise {@code null} */ - boolean addModel(LNGBooleanVector modelFromSolver, SATSolver solver, LNGIntVector relevantAllIndices, - ComputationHandler handler); + LNGEvent addModel(LNGBooleanVector modelFromSolver, SATSolver solver, LNGIntVector relevantAllIndices, + ComputationHandler handler); /** * All founds models since the last commit call are confirmed and cannot be * rolled back. *

* Calls the {@code commit()} routine of {@code handler}. - * @param handler the model enumeration handler, may be {@code null} - * @return {@code true} if the computation should continue, otherwise - * {@code false} + * @param handler the computation handler + * @return an event if the handler aborted the computation, + * otherwise {@code null} */ - boolean commit(ComputationHandler handler); + LNGEvent commit(ComputationHandler handler); /** * All found models since the last commit should be discarded. *

- * Calls the {@code rollback} routine of {@code handler}. - * @param handler the model enumeration handler, may be {@code null} - * @return {@code true} if the computation should continue, otherwise - * {@code false} + * The rollback should always be performed, even if the handler + * aborts the computation. + * @param handler the computation handler + * @return an event if the handler aborted the computation, + * otherwise {@code null} */ - boolean rollback(ComputationHandler handler); + LNGEvent rollback(ComputationHandler handler); /** * All found models since the last commit will be discarded and returned. *

* Calls the {@code rollback} routine of {@code handler}. * @param solver solver used for the enumeration - * @param handler the model enumeration handler, may be {@code null} + * @param handler the computation handler * @return list of all discarded models */ List rollbackAndReturnModels(final SATSolver solver, ComputationHandler handler); /** - * @return the committed state of the collector + * Returns the currently committed state of the collector. + * @return the currently committed state of the collector */ RESULT getResult(); } diff --git a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/ModelEnumerationConfig.java b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/ModelEnumerationConfig.java index d55b424d..03564a46 100644 --- a/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/ModelEnumerationConfig.java +++ b/src/main/java/com/booleworks/logicng/solvers/functions/modelenumeration/ModelEnumerationConfig.java @@ -6,8 +6,6 @@ import com.booleworks.logicng.configurations.Configuration; import com.booleworks.logicng.configurations.ConfigurationType; -import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.solvers.functions.ModelEnumerationFunction; import com.booleworks.logicng.solvers.functions.modelenumeration.splitprovider.MostCommonVariablesProvider; @@ -18,7 +16,6 @@ */ public class ModelEnumerationConfig extends Configuration { - final ComputationHandler handler; final ModelEnumerationStrategy strategy; /** @@ -27,7 +24,6 @@ public class ModelEnumerationConfig extends Configuration { */ private ModelEnumerationConfig(final Builder builder) { super(ConfigurationType.MODEL_ENUMERATION); - handler = builder.handler; strategy = builder.strategy; } @@ -45,24 +41,12 @@ public static Builder builder() { * @since 3.0.0 */ public static class Builder { - private ComputationHandler handler = NopHandler.get(); private ModelEnumerationStrategy strategy = DefaultModelEnumerationStrategy.builder().build(); private Builder() { // Initialize only via factory } - /** - * Sets the model enumeration handler for this function. The default is - * no handler. - * @param handler the handler, may be {@code null} - * @return the current builder - */ - public Builder handler(final ComputationHandler handler) { - this.handler = handler; - return this; - } - /** * Sets the model enumeration strategy for this function. The default is * the {@link DefaultModelEnumerationStrategy} with the diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/IncWBO.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/IncWBO.java index 8d4eee1c..186ffdf9 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/IncWBO.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/IncWBO.java @@ -22,15 +22,13 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.datastructures.Tristate.FALSE; -import static com.booleworks.logicng.datastructures.Tristate.UNDEF; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; import com.booleworks.logicng.util.Pair; @@ -86,7 +84,7 @@ public IncWBO(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { nbInitialVariables = nVars(); if (currentWeight == 1) { problemType = ProblemType.UNWEIGHTED; @@ -96,10 +94,10 @@ public MaxSATResult search() { initSymmetry(); } if (problemType == ProblemType.UNWEIGHTED || weightStrategy == MaxSATConfig.WeightStrategy.NONE) { - return normalSearch(); + return normalSearch(handler); } else if (weightStrategy == MaxSATConfig.WeightStrategy.NORMAL || weightStrategy == MaxSATConfig.WeightStrategy.DIVERSIFY) { - return weightSearch(); + return weightSearch(handler); } throw new IllegalArgumentException("Unknown problem type."); } @@ -300,14 +298,14 @@ protected void symmetryBreaking() { } @Override - protected MaxSATResult weightSearch() { + protected LNGResult weightSearch(final ComputationHandler handler) { assert weightStrategy == MaxSATConfig.WeightStrategy.NORMAL || weightStrategy == MaxSATConfig.WeightStrategy.DIVERSIFY; - final Tristate unsatResult = unsatSearch(); - if (unsatResult == UNDEF) { - return MaxSATResult.UNDEF; - } else if (unsatResult == FALSE) { - return MaxSATResult.UNSATISFIABLE; + final LNGResult unsatResult = unsatSearch(handler); + if (!unsatResult.isSuccess()) { + return LNGResult.aborted(unsatResult.getAbortionEvent()); + } else if (!unsatResult.getResult()) { + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } initAssumptions(assumptions); updateCurrentWeight(weightStrategy); @@ -320,10 +318,10 @@ protected MaxSATResult weightSearch() { assumptions.push(LNGCoreSolver.not(softClauses.get(i).assumptionVar())); } } - final Tristate res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == FALSE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (!res.getResult()) { nbCores++; assert solver.assumptionsConflict().size() > 0; final int coreCost = computeCostCore(solver.assumptionsConflict()); @@ -331,8 +329,9 @@ protected MaxSATResult weightSearch() { if (verbosity != MaxSATConfig.Verbosity.NONE) { output.printf("c LB : %d CS : %d W : %d%n", lbCost, solver.assumptionsConflict().size(), coreCost); } - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } relaxCore(solver.assumptionsConflict(), coreCost); incrementalBuildWeightSolver(weightStrategy); @@ -350,7 +349,7 @@ protected MaxSATResult weightSearch() { output.println("o " + lbCost); } } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { updateCurrentWeight(weightStrategy); final int cost = incComputeCostModel(solver.model()); @@ -365,9 +364,12 @@ protected MaxSATResult weightSearch() { if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } incrementalBuildWeightSolver(weightStrategy); } @@ -402,12 +404,12 @@ protected int incComputeCostModel(final LNGBooleanVector currentModel) { } @Override - protected MaxSATResult normalSearch() { - final Tristate unsatResult = unsatSearch(); - if (unsatResult == UNDEF) { - return MaxSATResult.UNDEF; - } else if (unsatResult == FALSE) { - return MaxSATResult.UNSATISFIABLE; + protected LNGResult normalSearch(final ComputationHandler handler) { + final LNGResult unsatResult = unsatSearch(handler); + if (!unsatResult.isSuccess()) { + return LNGResult.aborted(unsatResult.getAbortionEvent()); + } else if (!unsatResult.getResult()) { + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } initAssumptions(assumptions); solver = rebuildSolver(); @@ -419,10 +421,10 @@ protected MaxSATResult normalSearch() { assumptions.push(LNGCoreSolver.not(softClauses.get(i).assumptionVar())); } } - final Tristate res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == FALSE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (!res.getResult()) { nbCores++; assert solver.assumptionsConflict().size() > 0; final int coreCost = computeCostCore(solver.assumptionsConflict()); @@ -434,10 +436,11 @@ protected MaxSATResult normalSearch() { if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } relaxCore(solver.assumptionsConflict(), coreCost); } else { @@ -448,7 +451,7 @@ protected MaxSATResult normalSearch() { output.println("o " + lbCost); } saveModel(solver.model()); - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } } diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearSU.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearSU.java index 00898b6d..4f89fd77 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearSU.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearSU.java @@ -22,15 +22,16 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.CardinalityEncoding; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.Verbosity; import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.datastructures.LNGSoftClause; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -82,7 +83,7 @@ public LinearSU(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { nbInitialVariables = nVars(); if (currentWeight == 1) { problemType = ProblemType.UNWEIGHTED; @@ -91,18 +92,17 @@ public MaxSATResult search() { } if (problemType == ProblemType.WEIGHTED) { if (bmoMode && isBmo) { - return bmoSearch(); + return bmoSearch(handler); } else { - return normalSearch(); + return normalSearch(handler); } } else { - return normalSearch(); + return normalSearch(handler); } } - protected MaxSATResult bmoSearch() { + protected LNGResult bmoSearch(final ComputationHandler handler) { assert orderWeights.size() > 0; - Tristate res; initRelaxation(); int currentWeight = orderWeights.get(0); final int minWeight = orderWeights.get(orderWeights.size() - 1); @@ -113,11 +113,11 @@ protected MaxSATResult bmoSearch() { int localCost = 0; ubCost = 0; while (true) { - res = searchSATSolver(solver, handler); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; + final LNGResult res = searchSATSolver(solver, handler); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); } - if (res == Tristate.TRUE) { + if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), currentWeight); if (currentWeight == minWeight) { @@ -126,14 +126,17 @@ protected MaxSATResult bmoSearch() { output.println("o " + (newCost + lbCost)); } ubCost = newCost + lbCost; - if (newCost > 0 && !foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + if (newCost > 0) { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } } else if (verbosity != Verbosity.NONE) { output.printf("c BMO-UB : %d (Function %d/%d)%n", newCost, posWeight + 1, orderWeights.size()); } if (newCost == 0 && currentWeight == minWeight) { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { if (newCost == 0) { functions.push(new LNGIntVector(objFunction)); @@ -159,9 +162,9 @@ protected MaxSATResult bmoSearch() { if (currentWeight == minWeight) { if (model.size() == 0) { assert nbSatisfiable == 0; - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { functions.push(new LNGIntVector(objFunction)); @@ -170,8 +173,9 @@ protected MaxSATResult bmoSearch() { posWeight++; currentWeight = orderWeights.get(posWeight); localCost = 0; - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } solver = rebuildBMO(functions, weights, currentWeight); if (verbosity != Verbosity.NONE) { @@ -182,15 +186,14 @@ protected MaxSATResult bmoSearch() { } } - protected MaxSATResult normalSearch() { - Tristate res; + protected LNGResult normalSearch(final ComputationHandler handler) { initRelaxation(); solver = rebuildSolver(1); while (true) { - res = searchSATSolver(solver, handler); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); saveModel(solver.model()); @@ -199,7 +202,7 @@ protected MaxSATResult normalSearch() { } if (newCost == 0) { ubCost = newCost; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { if (problemType == ProblemType.WEIGHTED) { if (!encoder.hasPBEncoding()) { @@ -215,17 +218,18 @@ protected MaxSATResult normalSearch() { } } ubCost = newCost; - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } } } else { nbCores++; if (model.size() == 0) { assert nbSatisfiable == 0; - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } } diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearUS.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearUS.java index 0a57b912..8cd89dd8 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearUS.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/LinearUS.java @@ -22,11 +22,11 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - import com.booleworks.logicng.collections.LNGIntVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -69,36 +69,35 @@ public LinearUS(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { if (problemType == ProblemType.WEIGHTED) { throw new IllegalStateException("Error: Currently LinearUS does not support weighted MaxSAT instances."); } switch (incrementalStrategy) { case NONE: - return none(); + return none(handler); case ITERATIVE: if (encoder.cardEncoding() != MaxSATConfig.CardinalityEncoding.TOTALIZER) { throw new IllegalStateException( "Error: Currently iterative encoding in LinearUS only supports the Totalizer encoding."); } - return iterative(); + return iterative(handler); default: throw new IllegalArgumentException("Unknown incremental strategy: " + incrementalStrategy); } } - protected MaxSATResult none() { + protected LNGResult none(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); final LNGIntVector assumptions = new LNGIntVector(); encoder.setIncremental(MaxSATConfig.IncrementalStrategy.NONE); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); saveModel(solver.model()); @@ -107,15 +106,16 @@ protected MaxSATResult none() { } ubCost = newCost; if (nbSatisfiable == 1) { - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } if (encoder.cardEncoding() == MaxSATConfig.CardinalityEncoding.MTOTALIZER) { encoder.setModulo((int) Math.ceil(Math.sqrt(ubCost + 1.0))); } encoder.encodeCardinality(solver, objFunction, 0); } else { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { lbCost++; @@ -123,18 +123,21 @@ protected MaxSATResult none() { output.println("c LB : " + lbCost); } if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else if (lbCost == ubCost) { if (nbSatisfiable > 0) { if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); + } + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; } solver = rebuildSolver(); encoder.encodeCardinality(solver, objFunction, lbCost); @@ -142,19 +145,18 @@ protected MaxSATResult none() { } } - protected MaxSATResult iterative() { + protected LNGResult iterative(final ComputationHandler handler) { assert encoder.cardEncoding() == MaxSATConfig.CardinalityEncoding.TOTALIZER; nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); final LNGIntVector assumptions = new LNGIntVector(); encoder.setIncremental(MaxSATConfig.IncrementalStrategy.ITERATIVE); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); saveModel(solver.model()); @@ -163,15 +165,16 @@ protected MaxSATResult iterative() { } ubCost = newCost; if (nbSatisfiable == 1) { - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } for (int i = 0; i < objFunction.size(); i++) { assumptions.push(LNGCoreSolver.not(objFunction.get(i))); } } else { assert lbCost == ubCost; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { nbCores++; @@ -180,20 +183,21 @@ protected MaxSATResult iterative() { output.println("c LB : " + lbCost); } if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } if (lbCost == ubCost) { if (nbSatisfiable > 0) { if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } } - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } if (!encoder.hasCardEncoding()) { encoder.buildCardinality(solver, objFunction, lbCost); diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MSU3.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MSU3.java index d50df4d7..e4652bf4 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MSU3.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MSU3.java @@ -22,15 +22,16 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.CardinalityEncoding; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.IncrementalStrategy; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.Verbosity; import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -79,28 +80,27 @@ public MSU3(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { if (problemType == ProblemType.WEIGHTED) { throw new IllegalStateException( "Error: Currently algorithm MSU3 does not support weighted MaxSAT instances."); } switch (incrementalStrategy) { case NONE: - return none(); + return none(handler); case ITERATIVE: if (encoder.cardEncoding() != CardinalityEncoding.TOTALIZER) { throw new IllegalStateException( "Error: Currently iterative encoding in MSU3 only supports the Totalizer encoding."); } - return iterative(); + return iterative(handler); default: throw new IllegalArgumentException("Unknown incremental strategy: " + incrementalStrategy); } } - protected MaxSATResult none() { + protected LNGResult none(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); final LNGIntVector assumptions = new LNGIntVector(); @@ -111,10 +111,10 @@ protected MaxSATResult none() { coreMapping.put(softClauses.get(i).assumptionVar(), i); } while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); saveModel(solver.model()); @@ -123,14 +123,15 @@ protected MaxSATResult none() { } ubCost = newCost; if (nbSatisfiable == 1) { - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } for (int i = 0; i < objFunction.size(); i++) { assumptions.push(LNGCoreSolver.not(objFunction.get(i))); } } else { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { lbCost++; @@ -139,15 +140,18 @@ protected MaxSATResult none() { output.println("c LB : " + lbCost); } if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else if (lbCost == ubCost) { assert nbSatisfiable > 0; if (verbosity != Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); + } } sumSizeCores += solver.assumptionsConflict().size(); for (int i = 0; i < solver.assumptionsConflict().size(); i++) { @@ -172,13 +176,12 @@ protected MaxSATResult none() { } } - protected MaxSATResult iterative() { + protected LNGResult iterative(final ComputationHandler handler) { if (encoder.cardEncoding() != CardinalityEncoding.TOTALIZER) { throw new IllegalStateException( "Error: Currently algorithm MSU3 with iterative encoding only supports the totalizer encoding."); } nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); final LNGIntVector assumptions = new LNGIntVector(); @@ -191,10 +194,10 @@ protected MaxSATResult iterative() { coreMapping.put(softClauses.get(i).assumptionVar(), i); } while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); saveModel(solver.model()); @@ -203,15 +206,16 @@ protected MaxSATResult iterative() { } ubCost = newCost; if (nbSatisfiable == 1) { - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } for (int i = 0; i < objFunction.size(); i++) { assumptions.push(LNGCoreSolver.not(objFunction.get(i))); } } else { assert lbCost == newCost; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { lbCost++; @@ -220,21 +224,22 @@ protected MaxSATResult iterative() { output.println("c LB : " + lbCost); } if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } if (lbCost == ubCost) { assert nbSatisfiable > 0; if (verbosity != Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } sumSizeCores += solver.assumptionsConflict().size(); if (solver.assumptionsConflict().size() == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } joinObjFunction.clear(); for (int i = 0; i < solver.assumptionsConflict().size(); i++) { diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MaxSAT.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MaxSAT.java index 1c6181fe..eaeb4518 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MaxSAT.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/MaxSAT.java @@ -22,17 +22,17 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; +import static com.booleworks.logicng.handlers.events.ComputationFinishedEvent.MAX_SAT_CALL_FINISHED; +import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.MAX_SAT_CALL_STARTED; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.Verbosity; import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; -import com.booleworks.logicng.handlers.events.ComputationFinishedEvent; -import com.booleworks.logicng.handlers.events.ComputationStartedEvent; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.MaxSatNewLowerBoundEvent; import com.booleworks.logicng.handlers.events.MaxSatNewUpperBoundEvent; import com.booleworks.logicng.solvers.datastructures.LNGHardClause; @@ -68,6 +68,7 @@ public enum ProblemType { public enum MaxSATResult { UNSATISFIABLE, OPTIMUM, + @Deprecated // TODO remove UNDEF UNDEF } @@ -77,7 +78,6 @@ public enum MaxSATResult { final LNGVector hardClauses; final LNGIntVector orderWeights; protected Verbosity verbosity; - protected ComputationHandler handler; int hardWeight; ProblemType problemType; int nbVars; @@ -116,7 +116,6 @@ protected MaxSAT(final FormulaFactory f, final MaxSATConfig config) { nbSatisfiable = 0; sumSizeCores = 0; orderWeights = new LNGIntVector(); - handler = NopHandler.get(); } /** @@ -131,23 +130,23 @@ public static void newSATVariable(final LNGCoreSolver s) { * Solves the formula that is currently loaded in the SAT solver with a set * of assumptions. * @param s the SAT solver - * @param satHandler a SAT handler + * @param handler the handler * @param assumptions the assumptions * @return the result of the solving process */ - public static Tristate searchSATSolver(final LNGCoreSolver s, final ComputationHandler satHandler, - final LNGIntVector assumptions) { - return s.internalSolve(satHandler, assumptions); + public static LNGResult searchSATSolver(final LNGCoreSolver s, final ComputationHandler handler, + final LNGIntVector assumptions) { + return s.internalSolve(handler, assumptions); } /** * Solves the formula without assumptions. - * @param s the SAT solver - * @param satHandler a SAT handler + * @param s the SAT solver + * @param handler the handler * @return the result of the solving process */ - public static Tristate searchSATSolver(final LNGCoreSolver s, final ComputationHandler satHandler) { - return s.internalSolve(satHandler); + public static LNGResult searchSATSolver(final LNGCoreSolver s, final ComputationHandler handler) { + return s.internalSolve(handler); } /** @@ -156,12 +155,14 @@ public static Tristate searchSATSolver(final LNGCoreSolver s, final ComputationH * @return the result of the solving process * @throws IllegalArgumentException if the configuration was not valid */ - public final MaxSATResult search(final ComputationHandler handler) { - this.handler = handler; - handler.shouldResume(ComputationStartedEvent.MAX_SAT_CALL_STARTED); - final MaxSATResult result = search(); - handler.shouldResume(ComputationFinishedEvent.MAX_SAT_CALL_FINISHED); - this.handler = NopHandler.get(); + public final LNGResult search(final ComputationHandler handler) { + if (!handler.shouldResume(MAX_SAT_CALL_STARTED)) { + return LNGResult.aborted(MAX_SAT_CALL_STARTED); + } + final LNGResult result = internalSearch(handler); + if (!handler.shouldResume(MAX_SAT_CALL_FINISHED)) { + return LNGResult.aborted(MAX_SAT_CALL_FINISHED); + } return result; } @@ -170,7 +171,7 @@ public final MaxSATResult search(final ComputationHandler handler) { * @return the result of the solving process * @throws IllegalArgumentException if the configuration was not valid */ - public abstract MaxSATResult search(); + protected abstract LNGResult internalSearch(ComputationHandler handler); /** * Returns the number of variables in the working MaxSAT formula. @@ -399,12 +400,32 @@ public LNGBooleanVector model() { return model; } - boolean foundLowerBound(final int lowerBound) { - return handler.shouldResume(new MaxSatNewLowerBoundEvent(lowerBound)); + /** + * Informs the handler about a newly found lower bound and returns the + * event if the handler aborted the computation. Otherwise, {@code null} is + * returned. + * @param lowerBound the new lower bound + * @param handler the computation handler + * @return the event if the handler aborted the computation, otherwise + * {@code null} + */ + LNGEvent foundLowerBound(final int lowerBound, final ComputationHandler handler) { + final MaxSatNewLowerBoundEvent event = new MaxSatNewLowerBoundEvent(lowerBound); + return handler.shouldResume(event) ? null : event; } - boolean foundUpperBound(final int upperBound) { - return handler.shouldResume(new MaxSatNewUpperBoundEvent(upperBound)); + /** + * Informs the handler about a newly found upper bound and returns the + * event if the handler aborted the computation. Otherwise, {@code null} is + * returned. + * @param upperBound the new upper bound + * @param handler the computation handler + * @return the event if the handler aborted the computation, otherwise + * {@code null} + */ + LNGEvent foundUpperBound(final int upperBound, final ComputationHandler handler) { + final MaxSatNewUpperBoundEvent event = new MaxSatNewUpperBoundEvent(upperBound); + return handler.shouldResume(event) ? null : event; } /** diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/OLL.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/OLL.java index fc8b06c9..d2c838c6 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/OLL.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/OLL.java @@ -4,13 +4,12 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -64,14 +63,14 @@ public OLL(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { if (encoder.cardEncoding() != MaxSATConfig.CardinalityEncoding.TOTALIZER) { throw new IllegalStateException("Error: Currently OLL only supports the totalizer encoding."); } if (problemType == ProblemType.WEIGHTED) { - return weighted(); + return weighted(handler); } else { - return unweighted(); + return unweighted(handler); } } @@ -96,9 +95,8 @@ private LNGCoreSolver rebuildSolver() { return s; } - private MaxSATResult unweighted() { + private LNGResult unweighted(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); @@ -116,10 +114,10 @@ private MaxSATResult unweighted() { final LNGVector softCardinality = new LNGVector<>(); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final LNGBooleanVector model = solver.model(); final int newCost = computeCostModel(model, Integer.MAX_VALUE); @@ -128,24 +126,24 @@ private MaxSATResult unweighted() { ubCost = newCost; if (nbSatisfiable == 1) { if (newCost == 0) { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } for (int i = 0; i < nSoft(); i++) { assumptions.push(LNGCoreSolver.not(softClauses.get(i).assumptionVar())); } } else { assert lbCost == newCost; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } else { lbCost++; nbCores++; if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } if (lbCost == ubCost) { assert nbSatisfiable > 0; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } sumSizeCores += solver.assumptionsConflict().size(); final LNGIntVector softRelax = new LNGIntVector(); @@ -224,9 +222,8 @@ private MaxSATResult unweighted() { } } - private MaxSATResult weighted() { + private LNGResult weighted(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); @@ -245,10 +242,10 @@ private MaxSATResult weighted() { minWeight = currentWeight; while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == Tristate.TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final LNGBooleanVector model = solver.model(); final int newCost = computeCostModel(model, Integer.MAX_VALUE); @@ -295,10 +292,10 @@ private MaxSATResult weighted() { } } else { assert lbCost == newCost; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } - } else if (res == Tristate.FALSE) { + } else { // reduce the weighted to the unweighted case int minCore = Integer.MAX_VALUE; for (int i = 0; i < solver.assumptionsConflict().size(); i++) { @@ -319,11 +316,11 @@ private MaxSATResult weighted() { lbCost += minCore; nbCores++; if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } if (lbCost == ubCost) { assert nbSatisfiable > 0; - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } sumSizeCores += solver.assumptionsConflict().size(); final LNGIntVector softRelax = new LNGIntVector(); diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WBO.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WBO.java index ede1ee94..67da3faa 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WBO.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WBO.java @@ -22,17 +22,15 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.datastructures.Tristate.FALSE; -import static com.booleworks.logicng.datastructures.Tristate.TRUE; -import static com.booleworks.logicng.datastructures.Tristate.UNDEF; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.Verbosity; import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig.WeightStrategy; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; import com.booleworks.logicng.util.Pair; @@ -95,7 +93,7 @@ public WBO(final FormulaFactory f, final MaxSATConfig config) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { nbInitialVariables = nVars(); if (currentWeight == 1) { problemType = ProblemType.UNWEIGHTED; @@ -105,9 +103,9 @@ public MaxSATResult search() { initSymmetry(); } if (problemType == ProblemType.UNWEIGHTED || weightStrategy == WeightStrategy.NONE) { - return normalSearch(); + return normalSearch(handler); } else if (weightStrategy == WeightStrategy.NORMAL || weightStrategy == WeightStrategy.DIVERSIFY) { - return weightSearch(); + return weightSearch(handler); } throw new IllegalArgumentException("Unknown problem type."); } @@ -422,15 +420,15 @@ protected void symmetryBreaking() { indexSoftCore.clear(); } - Tristate unsatSearch() { + LNGResult unsatSearch(final ComputationHandler handler) { assert assumptions.size() == 0; solver = rebuildHardSolver(); - final Tristate res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return UNDEF; - } else if (res == FALSE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (!res.getResult()) { nbCores++; - } else if (res == TRUE) { + } else { nbSatisfiable++; final int cost = computeCostModel(solver.model(), Integer.MAX_VALUE); assert cost <= ubCost; @@ -444,22 +442,22 @@ Tristate unsatSearch() { return res; } - protected MaxSATResult weightSearch() { + protected LNGResult weightSearch(final ComputationHandler handler) { assert weightStrategy == WeightStrategy.NORMAL || weightStrategy == WeightStrategy.DIVERSIFY; - final Tristate unsatResult = unsatSearch(); - if (unsatResult == UNDEF) { - return MaxSATResult.UNDEF; - } else if (unsatResult == FALSE) { - return MaxSATResult.UNSATISFIABLE; + final LNGResult unsatResult = unsatSearch(handler); + if (!unsatResult.isSuccess()) { + return LNGResult.aborted(unsatResult.getAbortionEvent()); + } else if (!unsatResult.getResult()) { + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } initAssumptions(assumptions); updateCurrentWeight(weightStrategy); solver = rebuildWeightSolver(weightStrategy); while (true) { - final Tristate res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == FALSE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (!res.getResult()) { nbCores++; assert solver.assumptionsConflict().size() > 0; final int coreCost = computeCostCore(solver.assumptionsConflict()); @@ -467,8 +465,9 @@ protected MaxSATResult weightSearch() { if (verbosity != Verbosity.NONE) { output.printf("c LB : %d CS : %d W : %d%n", lbCost, solver.assumptionsConflict().size(), coreCost); } - if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); } relaxCore(solver.assumptionsConflict(), coreCost, assumptions); solver = rebuildWeightSolver(weightStrategy); @@ -486,7 +485,7 @@ protected MaxSATResult weightSearch() { output.println("o " + lbCost); } } - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { updateCurrentWeight(weightStrategy); final int cost = computeCostModel(solver.model(), Integer.MAX_VALUE); @@ -501,9 +500,12 @@ protected MaxSATResult weightSearch() { if (verbosity != Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } solver = rebuildWeightSolver(weightStrategy); } @@ -511,20 +513,20 @@ protected MaxSATResult weightSearch() { } } - protected MaxSATResult normalSearch() { - final Tristate unsatResult = unsatSearch(); - if (unsatResult == UNDEF) { - return MaxSATResult.UNDEF; - } else if (unsatResult == FALSE) { - return MaxSATResult.UNSATISFIABLE; + protected LNGResult normalSearch(final ComputationHandler handler) { + final LNGResult unsatResult = unsatSearch(handler); + if (!unsatResult.isSuccess()) { + return LNGResult.aborted(unsatResult.getAbortionEvent()); + } else if (!unsatResult.getResult()) { + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } initAssumptions(assumptions); solver = rebuildSolver(); while (true) { - final Tristate res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == FALSE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (!res.getResult()) { nbCores++; assert solver.assumptionsConflict().size() > 0; final int coreCost = computeCostCore(solver.assumptionsConflict()); @@ -536,9 +538,12 @@ protected MaxSATResult normalSearch() { if (verbosity != Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); + } } relaxCore(solver.assumptionsConflict(), coreCost, assumptions); solver = rebuildSolver(); @@ -550,7 +555,7 @@ protected MaxSATResult normalSearch() { output.println("o " + lbCost); } saveModel(solver.model()); - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } } } diff --git a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WMSU3.java b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WMSU3.java index 9c8f9631..5ccc8039 100644 --- a/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WMSU3.java +++ b/src/main/java/com/booleworks/logicng/solvers/maxsat/algorithms/WMSU3.java @@ -22,14 +22,13 @@ package com.booleworks.logicng.solvers.maxsat.algorithms; -import static com.booleworks.logicng.datastructures.Tristate.TRUE; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; - import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.solvers.maxsat.encodings.Encoder; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; @@ -110,7 +109,7 @@ protected static boolean subsetSum(final LNGIntVector set, final int sum) { } @Override - public MaxSATResult search() { + protected LNGResult internalSearch(final ComputationHandler handler) { if (problemType == ProblemType.UNWEIGHTED) { throw new IllegalStateException( "Error: Currently algorithm WMSU3 does not support unweighted MaxSAT instances."); @@ -123,25 +122,24 @@ public MaxSATResult search() { } switch (incrementalStrategy) { case NONE: - return none(); + return none(handler); case ITERATIVE: if (isBmo) { if (encoder.cardEncoding() != MaxSATConfig.CardinalityEncoding.TOTALIZER) { throw new IllegalStateException( "Error: Currently iterative encoding in WMSU3 only supports the Totalizer encoding."); } - return iterativeBmo(); + return iterativeBmo(handler); } else { - return iterative(); + return iterative(handler); } default: throw new IllegalArgumentException("Unknown incremental strategy: " + incrementalStrategy); } } - protected MaxSATResult iterative() { + protected LNGResult iterative(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); encoder.setIncremental(MaxSATConfig.IncrementalStrategy.ITERATIVE); @@ -153,10 +151,10 @@ protected MaxSATResult iterative() { final LNGIntVector fullObjFunction = new LNGIntVector(); final LNGIntVector fullCoeffsFunction = new LNGIntVector(); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); if (newCost < ubCost || nbSatisfiable == 1) { @@ -169,9 +167,12 @@ protected MaxSATResult iterative() { if (ubCost == 0 || lbCost == ubCost || (currentWeight == 1 && nbSatisfiable > 1)) { assert lbCost == ubCost; assert nbSatisfiable > 0; - return MaxSATResult.OPTIMUM; - } else if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } for (int i = 0; i < nSoft(); i++) { if (softClauses.get(i).weight() >= currentWeight && !activeSoft.get(i)) { @@ -181,15 +182,18 @@ protected MaxSATResult iterative() { } else { nbCores++; if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else if (lbCost == ubCost) { assert nbSatisfiable > 0; if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); + } } sumSizeCores += solver.assumptionsConflict().size(); objFunction.clear(); @@ -235,9 +239,8 @@ protected MaxSATResult iterative() { } } - protected MaxSATResult none() { + protected LNGResult none(final ComputationHandler handler) { nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); encoder.setIncremental(MaxSATConfig.IncrementalStrategy.NONE); @@ -247,10 +250,10 @@ protected MaxSATResult none() { } assumptions.clear(); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); if (newCost < ubCost || nbSatisfiable == 1) { @@ -262,9 +265,12 @@ protected MaxSATResult none() { } if (ubCost == 0 || lbCost == ubCost || (currentWeight == 1 && nbSatisfiable > 1)) { assert nbSatisfiable > 0; - return MaxSATResult.OPTIMUM; - } else if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } for (int i = 0; i < nSoft(); i++) { if (softClauses.get(i).weight() >= currentWeight && !activeSoft.get(i)) { @@ -274,15 +280,18 @@ protected MaxSATResult none() { } else { nbCores++; if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else if (lbCost == ubCost) { assert nbSatisfiable > 0; if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); + } } sumSizeCores += solver.assumptionsConflict().size(); for (int i = 0; i < solver.assumptionsConflict().size(); i++) { @@ -317,10 +326,9 @@ protected MaxSATResult none() { } } - protected MaxSATResult iterativeBmo() { + protected LNGResult iterativeBmo(final ComputationHandler handler) { assert isBmo; nbInitialVariables = nVars(); - Tristate res; initRelaxation(); solver = rebuildSolver(); encoder.setIncremental(MaxSATConfig.IncrementalStrategy.ITERATIVE); @@ -346,10 +354,10 @@ protected MaxSATResult iterativeBmo() { bmoEncodings.push(e); firstEncoding.push(true); while (true) { - res = searchSATSolver(solver, handler, assumptions); - if (!handler.shouldResume(NO_EVENT)) { - return MaxSATResult.UNDEF; - } else if (res == TRUE) { + final LNGResult res = searchSATSolver(solver, handler, assumptions); + if (!res.isSuccess()) { + return LNGResult.aborted(res.getAbortionEvent()); + } else if (res.getResult()) { nbSatisfiable++; final int newCost = computeCostModel(solver.model(), Integer.MAX_VALUE); if (newCost < ubCost || nbSatisfiable == 1) { @@ -361,9 +369,12 @@ protected MaxSATResult iterativeBmo() { } if (nbSatisfiable == 1) { if (ubCost == 0) { - return MaxSATResult.OPTIMUM; - } else if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); + } } assert orderWeights.size() > 0; assert orderWeights.get(0) > 1; @@ -376,10 +387,11 @@ protected MaxSATResult iterativeBmo() { } } else { if (currentWeight == 1 || currentWeight == minWeight) { - return MaxSATResult.OPTIMUM; + return LNGResult.of(MaxSATResult.OPTIMUM); } else { - if (!foundUpperBound(ubCost)) { - return MaxSATResult.UNDEF; + final LNGEvent upperBoundEvent = foundUpperBound(ubCost, handler); + if (upperBoundEvent != null) { + return LNGResult.aborted(upperBoundEvent); } assumptions.clear(); final int previousWeight = currentWeight; @@ -422,15 +434,18 @@ protected MaxSATResult iterativeBmo() { output.println("c LB : " + lbCost); } if (nbSatisfiable == 0) { - return MaxSATResult.UNSATISFIABLE; + return LNGResult.of(MaxSATResult.UNSATISFIABLE); } else if (lbCost == ubCost) { assert nbSatisfiable > 0; if (verbosity != MaxSATConfig.Verbosity.NONE) { output.println("c LB = UB"); } - return MaxSATResult.OPTIMUM; - } else if (!foundLowerBound(lbCost)) { - return MaxSATResult.UNDEF; + return LNGResult.of(MaxSATResult.OPTIMUM); + } else { + final LNGEvent lowerBoundEvent = foundLowerBound(lbCost, handler); + if (lowerBoundEvent != null) { + return LNGResult.aborted(lowerBoundEvent); + } } sumSizeCores += solver.assumptionsConflict().size(); joinObjFunction.clear(); diff --git a/src/main/java/com/booleworks/logicng/solvers/sat/LNGCoreSolver.java b/src/main/java/com/booleworks/logicng/solvers/sat/LNGCoreSolver.java index ace2f580..d6b7a13f 100644 --- a/src/main/java/com/booleworks/logicng/solvers/sat/LNGCoreSolver.java +++ b/src/main/java/com/booleworks/logicng/solvers/sat/LNGCoreSolver.java @@ -22,10 +22,12 @@ package com.booleworks.logicng.solvers.sat; +import static com.booleworks.logicng.datastructures.Tristate.FALSE; +import static com.booleworks.logicng.datastructures.Tristate.TRUE; import static com.booleworks.logicng.datastructures.Tristate.UNDEF; import static com.booleworks.logicng.handlers.events.ComputationFinishedEvent.SAT_CALL_FINISHED; +import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.BACKBONE_COMPUTATION_STARTED; import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.SAT_CALL_STARTED; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; import static com.booleworks.logicng.handlers.events.SimpleEvent.SAT_CONFLICT_DETECTED; import com.booleworks.logicng.backbones.Backbone; @@ -38,7 +40,9 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.SolverState; @@ -130,10 +134,6 @@ public class LNGCoreSolver { protected int clausesLiterals = 0; protected int learntsLiterals = 0; - // SAT handler - protected ComputationHandler handler = NopHandler.get(); - protected boolean canceledByHandler = false; - // Proof generating information protected LNGVector pgOriginalClauses = new LNGVector<>(); protected LNGVector pgProof = new LNGVector<>(); @@ -433,16 +433,16 @@ public boolean addClause(final LNGIntVector ps, final Proposition proposition) { oc = new LNGIntVector(); for (i = 0, p = LIT_UNDEF; i < ps.size(); i++) { oc.push(ps.get(i)); - if (value(ps.get(i)) == Tristate.TRUE || ps.get(i) == not(p) || value(ps.get(i)) == Tristate.FALSE) { + if (value(ps.get(i)) == TRUE || ps.get(i) == not(p) || value(ps.get(i)) == FALSE) { flag = true; } } } for (i = 0, j = 0, p = LIT_UNDEF; i < ps.size(); i++) { - if (value(ps.get(i)) == Tristate.TRUE || ps.get(i) == not(p)) { + if (value(ps.get(i)) == TRUE || ps.get(i) == not(p)) { return true; - } else if (value(ps.get(i)) != Tristate.FALSE && ps.get(i) != p) { + } else if (value(ps.get(i)) != FALSE && ps.get(i) != p) { p = ps.get(i); ps.set(j++, p); } @@ -488,80 +488,64 @@ public boolean addClause(final LNGIntVector ps, final Proposition proposition) { } /** - * Solves the formula currently stored in the solver. Returns - * {@link Tristate#TRUE} if the formula is satisfiable (SAT), - * {@link Tristate#FALSE} if the formula is unsatisfiable (UNSAT), or - * {@link Tristate#UNDEF} if the computation was canceled by a - * {@link SATHandler}. If {@code null} is passed as handler, the solver will - * run until the satisfiability is decided. + * Solves the formula currently stored in the solver and returns whether + * it is satisfiable or not. If the handler aborts the computation earlier, + * a result with the respective abortion event is returned. * @param handler a handler - * @return {@link Tristate#TRUE} if the formula is satisfiable, - * {@link Tristate#FALSE} if the formula is not satisfiable, or - * {@link Tristate#UNDEF} if the computation was canceled. - */ - public Tristate internalSolve(final ComputationHandler handler) { - this.handler = handler; - final Tristate result = internalSolve(); - this.handler = NopHandler.get(); - return result; - } - - public Tristate internalSolve() { - handler.shouldResume(SAT_CALL_STARTED); + * @return the result of the solve call + */ + public LNGResult internalSolve(final ComputationHandler handler) { + if (!handler.shouldResume(SAT_CALL_STARTED)) { + return LNGResult.aborted(SAT_CALL_STARTED); + } model.clear(); assumptionsConflict.clear(); if (!ok) { - return Tristate.FALSE; + return LNGResult.of(false); + } + LNGResult status = LNGResult.of(UNDEF); + while (status.isSuccess() && status.getResult() == UNDEF) { + status = search(handler); } - Tristate status = Tristate.UNDEF; - while (status == Tristate.UNDEF && !canceledByHandler) { - status = search(); + + if (!status.isSuccess()) { + cancelUntil(0); + return LNGResult.aborted(status.getAbortionEvent()); } - if (config.proofGeneration && assumptions.empty() && status == Tristate.FALSE) { + final boolean result = status.getResult() == TRUE; + + if (config.proofGeneration && assumptions.empty() && !result) { pgProof.push(LNGIntVector.of(0)); } - if (status == Tristate.TRUE) { + if (result) { model = new LNGBooleanVector(vars.size()); for (final LNGVariable v : vars) { - model.push(v.assignment() == Tristate.TRUE); + model.push(v.assignment() == TRUE); } - } else if (status == Tristate.FALSE && assumptionsConflict.empty()) { + } else if (assumptionsConflict.empty()) { ok = false; } - handler.shouldResume(SAT_CALL_FINISHED); cancelUntil(0); - canceledByHandler = false; - return status; - } - - /** - * Sets (or clears) the SAT handler which should be used for subsequent SAT - * calls. - * @param handler the handler to be used - */ - public void setHandler(final ComputationHandler handler) { - this.handler = handler; + if (!handler.shouldResume(SAT_CALL_FINISHED)) { + return LNGResult.aborted(SAT_CALL_FINISHED); + } + return LNGResult.of(result); } /** - * Solves the formula currently stored in the solver together with the given - * assumption literals. Returns {@link Tristate#TRUE} if the formula and the - * assumptions are satisfiable (SAT), {@link Tristate#FALSE} if the formula - * and the assumptions are not satisfiable together (UNSAT), or - * {@link Tristate#UNDEF} if the computation was canceled by a - * {@link SATHandler}. If {@code null} is passed as handler, the solver will - * run until the satisfiability is decided. + * Solves the formula currently stored in the solver together with the + * given assumption literals and returns whether it is satisfiable or not. + * If the handler aborts the computation earlier, a result with the + * respective abortion event is returned. * @param handler a handler * @param assumptions the assumptions as a given vector of literals - * @return {@link Tristate#TRUE} if the formula and the assumptions are - * satisfiable, {@link Tristate#FALSE} if they are not satisfiable, - * or {@link Tristate#UNDEF} if the computation was canceled. + * @return the result of the solve call */ - public Tristate internalSolve(final ComputationHandler handler, final LNGIntVector assumptions) { + public LNGResult internalSolve(final ComputationHandler handler, final LNGIntVector assumptions) { this.assumptions = new LNGIntVector(assumptions); - final Tristate result = internalSolve(handler); + final LNGResult result = internalSolve(handler); this.assumptions.clear(); return result; } @@ -800,7 +784,7 @@ protected void varBumpActivity(final int v, final double inc) { * @return {@code true} if the given clause is locked */ protected boolean locked(final LNGClause c) { - return value(c.get(0)) == Tristate.TRUE && v(c.get(0)).reason() != null && v(c.get(0)).reason() == c; + return value(c.get(0)) == TRUE && v(c.get(0)).reason() != null && v(c.get(0)).reason() == c; } /** @@ -831,7 +815,7 @@ protected void claBumpActivity(final LNGClause c) { * or {@code null} if it was a decision */ protected void uncheckedEnqueue(final int lit, final LNGClause reason) { - assert value(lit) == Tristate.UNDEF; + assert value(lit) == UNDEF; final LNGVariable var = v(lit); var.assign(Tristate.fromBool(!sign(lit))); var.setReason(reason); @@ -917,17 +901,17 @@ protected LNGClause propagate() { final LNGVector wbin = watchesBin.get(p); for (int k = 0; k < wbin.size(); k++) { final int imp = wbin.get(k).blocker(); - if (value(imp) == Tristate.FALSE) { + if (value(imp) == FALSE) { return wbin.get(k).clause(); } - if (value(imp) == Tristate.UNDEF) { + if (value(imp) == UNDEF) { uncheckedEnqueue(imp, wbin.get(k).clause()); } } while (iInd < ws.size()) { final LNGWatcher i = ws.get(iInd); final int blocker = i.blocker(); - if (blocker != LIT_UNDEF && value(blocker) == Tristate.TRUE) { + if (blocker != LIT_UNDEF && value(blocker) == TRUE) { ws.set(jInd++, i); iInd++; continue; @@ -938,8 +922,8 @@ protected LNGClause propagate() { final int newWatch = findNewWatchForAtMostClause(c, p); if (newWatch == LIT_UNDEF) { for (int k = 0; k < c.atMostWatchers(); k++) { - if (c.get(k) != p && value(c.get(k)) != Tristate.FALSE) { - assert value(c.get(k)) == Tristate.UNDEF || value(c.get(k)) == Tristate.FALSE; + if (c.get(k) != p && value(c.get(k)) != FALSE) { + assert value(c.get(k)) == UNDEF || value(c.get(k)) == FALSE; uncheckedEnqueue(not(c.get(k)), c); } } @@ -967,13 +951,13 @@ protected LNGClause propagate() { iInd++; final int first = c.get(0); final LNGWatcher w = new LNGWatcher(c, first); - if (first != blocker && value(first) == Tristate.TRUE) { + if (first != blocker && value(first) == TRUE) { ws.set(jInd++, w); continue; } boolean foundWatch = false; for (int k = 2; k < c.size() && !foundWatch; k++) { - if (value(c.get(k)) != Tristate.FALSE) { + if (value(c.get(k)) != FALSE) { c.set(1, c.get(k)); c.set(k, falseLit); watches.get(not(c.get(1))).push(w); @@ -982,7 +966,7 @@ protected LNGClause propagate() { } if (!foundWatch) { ws.set(jInd++, w); - if (value(first) == Tristate.FALSE) { + if (value(first) == FALSE) { confl = c; qhead = trail.size(); while (iInd < ws.size()) { @@ -1018,7 +1002,7 @@ protected boolean litRedundant(final int p, final int abstractLevels, final LNGI analyzeStack.pop(); if (c.isAtMost()) { for (int i = 0; i < c.size(); i++) { - if (value(c.get(i)) != Tristate.TRUE) { + if (value(c.get(i)) != TRUE) { continue; } final int q = not(c.get(i)); @@ -1037,8 +1021,8 @@ protected boolean litRedundant(final int p, final int abstractLevels, final LNGI } } } else { - if (c.size() == 2 && value(c.get(0)) == Tristate.FALSE) { - assert value(c.get(1)) == Tristate.TRUE; + if (c.size() == 2 && value(c.get(0)) == FALSE) { + assert value(c.get(1)) == TRUE; final int tmp = c.get(0); c.set(0, c.get(1)); c.set(1, tmp); @@ -1094,7 +1078,7 @@ protected void analyzeAssumptionConflict(final int p) { } } else { for (int j = 0; j < c.size(); j++) { - if (value(c.get(j)) == Tristate.TRUE && v(c.get(j)).level() > 0) { + if (value(c.get(j)) == TRUE && v(c.get(j)).level() > 0) { seen.set(var(c.get(j)), true); } } @@ -1111,7 +1095,7 @@ protected void cancelUntil(final int level) { for (int c = trail.size() - 1; c >= trailLim.get(level); c--) { final int x = var(trail.get(c)); final LNGVariable v = vars.get(x); - v.assign(Tristate.UNDEF); + v.assign(UNDEF); v.setPolarity(!computingBackbone && sign(trail.get(c))); insertVarOrder(x); } @@ -1176,9 +1160,9 @@ public LNGVector pgProof() { * {@code UNDEF} if the state is not known yet (restart) or the * handler canceled the computation */ - protected Tristate search() { + protected LNGResult search(final ComputationHandler handler) { if (!ok) { - return Tristate.FALSE; + return LNGResult.of(FALSE); } final LNGIntVector learntClause = new LNGIntVector(); selectionOrderIdx = 0; @@ -1186,8 +1170,7 @@ protected Tristate search() { final LNGClause confl = propagate(); if (confl != null) { if (!handler.shouldResume(SAT_CONFLICT_DETECTED)) { - canceledByHandler = true; - return Tristate.UNDEF; + return LNGResult.aborted(SAT_CONFLICT_DETECTED); } conflicts++; conflictsRestarts++; @@ -1195,7 +1178,7 @@ protected Tristate search() { varDecay += 0.01; } if (decisionLevel() == 0) { - return Tristate.FALSE; + return LNGResult.of(FALSE); } trailQueue.push(trail.size()); if (conflictsRestarts > LB_BLOCKING_RESTART && lbdQueue.valid() && @@ -1238,7 +1221,7 @@ protected Tristate search() { if (lbdQueue.valid() && (lbdQueue.avg() * llConfig.factorK) > (sumLBD / conflictsRestarts)) { lbdQueue.fastClear(); cancelUntil(0); - return Tristate.UNDEF; + return LNGResult.of(UNDEF); } if (conflicts >= (curRestart * nbClausesBeforeReduce) && learnts.size() > 0) { curRestart = (conflicts / nbClausesBeforeReduce) + 1; @@ -1248,16 +1231,16 @@ protected Tristate search() { int next = LIT_UNDEF; while (decisionLevel() < assumptions.size()) { final int p = assumptions.get(decisionLevel()); - if (value(p) == Tristate.TRUE) { + if (value(p) == TRUE) { trailLim.push(trail.size()); - } else if (value(p) == Tristate.FALSE) { + } else if (value(p) == FALSE) { if (config.proofGeneration) { final int drupLit = (var(p) + 1) * (-2 * (sign(p) ? 1 : 0) + 1); pgOriginalClauses.push(new ProofInformation(LNGIntVector.of(drupLit), assumptionPropositions.get(decisionLevel()))); } analyzeAssumptionConflict(not(p)); - return Tristate.FALSE; + return LNGResult.of(FALSE); } else { if (config.proofGeneration) { final int drupLit = (var(p) + 1) * (-2 * (sign(p) ? 1 : 0) + 1); @@ -1271,7 +1254,7 @@ protected Tristate search() { if (next == LIT_UNDEF) { next = pickBranchLit(); if (next == LIT_UNDEF) { - return Tristate.TRUE; + return LNGResult.of(TRUE); } } trailLim.push(trail.size()); @@ -1299,7 +1282,7 @@ protected void analyze(final LNGClause conflictClause, final LNGIntVector outLea assert c != null; if (c.isAtMost()) { for (int j = 0; j < c.size(); j++) { - if (value(c.get(j)) != Tristate.TRUE) { + if (value(c.get(j)) != TRUE) { continue; } final int q = not(c.get(j)); @@ -1314,8 +1297,8 @@ protected void analyze(final LNGClause conflictClause, final LNGIntVector outLea } } } else { - if (p != LIT_UNDEF && c.size() == 2 && value(c.get(0)) == Tristate.FALSE) { - assert value(c.get(1)) == Tristate.TRUE; + if (p != LIT_UNDEF && c.size() == 2 && value(c.get(0)) == FALSE) { + assert value(c.get(1)) == TRUE; final int tmp = c.get(0); c.set(0, c.get(1)); c.set(1, tmp); @@ -1477,7 +1460,7 @@ protected void minimisationWithBinaryResolution(final LNGIntVector outLearnt) { int nb = 0; for (final LNGWatcher wbin : watchesBin.get(p)) { final int imp = wbin.blocker(); - if (permDiff.get(var(imp)) == myflag && value(imp) == Tristate.TRUE) { + if (permDiff.get(var(imp)) == myflag && value(imp) == TRUE) { nb++; permDiff.set(var(imp), myflag - 1); } @@ -1504,7 +1487,7 @@ protected void minimisationWithBinaryResolution(final LNGIntVector outLearnt) { protected void completeBacktrack() { for (int v = 0; v < vars.size(); v++) { final LNGVariable var = vars.get(v); - var.assign(Tristate.UNDEF); + var.assign(UNDEF); var.setReason(null); if (!orderHeap.inHeap(v) && var.decision()) { orderHeap.insert(v); @@ -1550,13 +1533,13 @@ public void addAtMost(final LNGIntVector ps, final int rhs) { int i; int j; for (i = j = 0, p = LIT_UNDEF; i < ps.size(); i++) { - if (value(ps.get(i)) == Tristate.TRUE) { + if (value(ps.get(i)) == TRUE) { k--; } else if (ps.get(i) == not(p)) { p = ps.get(i); j--; k--; - } else if (value(ps.get(i)) != Tristate.FALSE) { + } else if (value(ps.get(i)) != FALSE) { p = ps.get(i); ps.set(j++, p); } @@ -1605,7 +1588,7 @@ protected int findNewWatchForAtMostClause(final LNGClause c, final int p) { } if (c.get(q) == p) { for (int next = c.atMostWatchers(); next < c.size(); next++) { - if (value(c.get(next)) != Tristate.TRUE) { + if (value(c.get(next)) != TRUE) { final int newWatch = c.get(next); c.set(next, c.get(q)); c.set(q, newWatch); @@ -1753,7 +1736,7 @@ public LNGIntVector upZeroLiterals() { * @param type backbone type * @return the backbone projected to the relevant variables */ - public Backbone computeBackbone(final Collection variables, final BackboneType type) { + public LNGResult computeBackbone(final Collection variables, final BackboneType type) { return computeBackbone(variables, type, NopHandler.get()); } @@ -1766,26 +1749,33 @@ public Backbone computeBackbone(final Collection variables, final Back * @return the backbone projected to the relevant variables or {@code null} * if the computation was aborted by the handler */ - public Backbone computeBackbone(final Collection variables, final BackboneType type, - final ComputationHandler handler) { - final boolean sat = internalSolve(handler) == Tristate.TRUE; - if (!handler.shouldResume(NO_EVENT)) { - return null; - } - if (sat) { + public LNGResult computeBackbone(final Collection variables, final BackboneType type, + final ComputationHandler handler) { + if (!handler.shouldResume(BACKBONE_COMPUTATION_STARTED)) { + return LNGResult.aborted(BACKBONE_COMPUTATION_STARTED); + } + final SolverState stateBeforeBackbone = saveState(); + final LNGResult solveResult = internalSolve(handler); + final LNGResult result; + if (!solveResult.isSuccess()) { + result = LNGResult.aborted(solveResult.getAbortionEvent()); + } else if (solveResult.getResult()) { computingBackbone = true; final List relevantVarIndices = getRelevantVarIndices(variables); initBackboneDS(relevantVarIndices); - computeBackbone(relevantVarIndices, type, handler); - if (!handler.shouldResume(NO_EVENT)) { - return null; + final LNGEvent backboneEvent = computeBackbone(relevantVarIndices, type, handler); + if (backboneEvent != null) { + result = LNGResult.aborted(backboneEvent); + } else { + final Backbone backbone = buildBackbone(variables, type); + result = LNGResult.of(backbone); } - final Backbone backbone = buildBackbone(variables, type); computingBackbone = false; - return backbone; } else { - return Backbone.unsatBackbone(); + result = LNGResult.of(Backbone.unsatBackbone()); } + loadState(stateBeforeBackbone); + return result; } /** @@ -1827,20 +1817,20 @@ protected void initBackboneDS(final List variables) { * @param type the type of the backbone * @param handler the handler */ - protected void computeBackbone(final List variables, final BackboneType type, final ComputationHandler handler) { + protected LNGEvent computeBackbone(final List variables, final BackboneType type, final ComputationHandler handler) { createInitialCandidates(variables, type); while (!backboneCandidates.isEmpty()) { final int lit = backboneCandidates.pop(); - final boolean sat = solveWithLit(lit, handler); - if (!handler.shouldResume(NO_EVENT)) { - return; - } - if (sat) { + final LNGResult satResult = solveWithLit(lit, handler); + if (!satResult.isSuccess()) { + return satResult.getAbortionEvent(); + } else if (satResult.getResult()) { refineUpperBound(); } else { addBackboneLiteral(lit); } } + return null; } /** @@ -1890,11 +1880,11 @@ protected void refineUpperBound() { * @param handler the handler * @return {@code true} if satisfiable, otherwise {@code false} */ - protected boolean solveWithLit(final int lit, final ComputationHandler handler) { + protected LNGResult solveWithLit(final int lit, final ComputationHandler handler) { backboneAssumptions.push(not(lit)); - final boolean sat = internalSolve(handler, backboneAssumptions) == Tristate.TRUE; + final LNGResult result = internalSolve(handler, backboneAssumptions); backboneAssumptions.pop(); - return sat; + return result; } /** @@ -2012,7 +2002,7 @@ protected boolean isRotatable(final int lit) { * @param lit literal to add */ protected void addBackboneLiteral(final int lit) { - backboneMap.put(var(lit), sign(lit) ? Tristate.FALSE : Tristate.TRUE); + backboneMap.put(var(lit), sign(lit) ? FALSE : TRUE); backboneAssumptions.push(lit); } diff --git a/src/main/java/com/booleworks/logicng/solvers/sat/SATCall.java b/src/main/java/com/booleworks/logicng/solvers/sat/SATCall.java index f786e2a6..1094967a 100644 --- a/src/main/java/com/booleworks/logicng/solvers/sat/SATCall.java +++ b/src/main/java/com/booleworks/logicng/solvers/sat/SATCall.java @@ -1,18 +1,16 @@ package com.booleworks.logicng.solvers.sat; -import static com.booleworks.logicng.datastructures.Tristate.FALSE; -import static com.booleworks.logicng.datastructures.Tristate.TRUE; import static com.booleworks.logicng.solvers.sat.LNGCoreSolver.generateClauseVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.collections.LNGVector; import com.booleworks.logicng.datastructures.Assignment; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.FType; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.SolverState; @@ -54,7 +52,7 @@ public class SATCall implements AutoCloseable { private final LNGCoreSolver solver; private SolverState initialState; private int pgOriginalClausesLength = -1; - private Tristate satState; + private LNGResult satResult; SATCall(final SATSolver solverWrapper, final ComputationHandler handler, final List additionalPropositions, final List selectionOrder) { @@ -82,11 +80,10 @@ private void initAndSolve(final ComputationHandler handler, final List additionalPropositions) { @@ -105,15 +102,11 @@ private Additionals splitPropsIntoLiteralsAndFormulas(final List getSatResult() { + return satResult; } /** @@ -130,7 +123,7 @@ public Assignment model(final Collection variables) { if (variables == null) { throw new IllegalArgumentException("The given variables must not be null."); } - if (satState != TRUE) { + if (!satResult.isSuccess() || !satResult.getResult()) { return null; } else { final List unknowns = new ArrayList<>(); @@ -164,7 +157,7 @@ public UNSATCore unsatCore() { if (!solver.config().proofGeneration()) { throw new IllegalStateException("Cannot generate an unsat core if proof generation is not turned on"); } - if (satState != FALSE) { + if (!satResult.isSuccess() || satResult.getResult()) { return null; } return UnsatCoreFunction.get().apply(solverWrapper); @@ -181,7 +174,6 @@ public void close() { if (initialState != null) { solver.loadState(initialState); } - solver.setHandler(null); solver.finishSatCall(); } diff --git a/src/main/java/com/booleworks/logicng/solvers/sat/SATCallBuilder.java b/src/main/java/com/booleworks/logicng/solvers/sat/SATCallBuilder.java index 7550854d..e2db914f 100644 --- a/src/main/java/com/booleworks/logicng/solvers/sat/SATCallBuilder.java +++ b/src/main/java/com/booleworks/logicng/solvers/sat/SATCallBuilder.java @@ -1,12 +1,12 @@ package com.booleworks.logicng.solvers.sat; import com.booleworks.logicng.datastructures.Assignment; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.propositions.Proposition; import com.booleworks.logicng.propositions.StandardProposition; @@ -137,13 +137,10 @@ public SATCallBuilder selectionOrder(final List selectionOrde /** * Directly computes the satisfiability result with the current state of the - * builder. Returns {@link Tristate#TRUE} if the formula is satisfiable, - * {@link Tristate#FALSE} if the formula is not satisfiable, and - * {@link Tristate#UNDEF} if the SAT call was aborted by the - * {@link SATHandler handler}. + * builder. * @return the satisfiability result */ - public Tristate sat() { + public LNGResult sat() { try (final SATCall call = solve()) { return call.getSatResult(); } diff --git a/src/main/java/com/booleworks/logicng/transformations/AIGTransformation.java b/src/main/java/com/booleworks/logicng/transformations/AIGTransformation.java index 138b3a1b..6c7d9140 100644 --- a/src/main/java/com/booleworks/logicng/transformations/AIGTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/AIGTransformation.java @@ -12,6 +12,8 @@ import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.Or; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import java.util.LinkedHashSet; import java.util.Map; @@ -45,7 +47,11 @@ public AIGTransformation(final FormulaFactory f, final Map cac } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return LNGResult.of(transform(formula)); + } + + private Formula transform(final Formula formula) { switch (formula.type()) { case FALSE: case TRUE: @@ -63,7 +69,7 @@ public Formula apply(final Formula formula) { case OR: return transformOr((Or) formula); case PBC: - return apply(formula.cnf(f)); + return transform(formula.cnf(f)); default: throw new IllegalArgumentException("Could not process the formula type " + formula.type()); } diff --git a/src/main/java/com/booleworks/logicng/transformations/AbortableFormulaTransformation.java b/src/main/java/com/booleworks/logicng/transformations/AbortableFormulaTransformation.java deleted file mode 100644 index 97b61f9d..00000000 --- a/src/main/java/com/booleworks/logicng/transformations/AbortableFormulaTransformation.java +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 and MIT -// Copyright 2015-2023 Christoph Zengler -// Copyright 2023-20xx BooleWorks GmbH - -package com.booleworks.logicng.transformations; - -import com.booleworks.logicng.formulas.FormulaFactory; -import com.booleworks.logicng.handlers.ComputationHandler; - -/** - * An abortable formula transformation is a stateless transformation which can - * be aborted via a handler. So it does still not mutate any internal state, but - * *can* change the handler's state. Therefore, an abortable transformation with - * a given handler is *NOT* thread-safe. - * @version 3.0.0 - * @since 3.0.0 - */ -public abstract class AbortableFormulaTransformation extends StatelessFormulaTransformation { - protected final ComputationHandler handler; - - /** - * Constructor. - * @param f the formula factory to generate new formulas - * @param handler the handler for the transformation - **/ - protected AbortableFormulaTransformation(final FormulaFactory f, final ComputationHandler handler) { - super(f); - this.handler = handler; - } -} diff --git a/src/main/java/com/booleworks/logicng/transformations/Anonymizer.java b/src/main/java/com/booleworks/logicng/transformations/Anonymizer.java index 6b991f6f..e63822fe 100644 --- a/src/main/java/com/booleworks/logicng/transformations/Anonymizer.java +++ b/src/main/java/com/booleworks/logicng/transformations/Anonymizer.java @@ -8,6 +8,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; /** * An anonymizer replaces all variables in a formula with new variables @@ -78,15 +80,15 @@ public Substitution getSubstitution() { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { if (formula.variables(f).isEmpty()) { - return formula; + return LNGResult.of(formula); } for (final Variable variable : formula.variables(f)) { if (state.getSubstitution(variable) == null) { state.addMapping(variable, f.variable(prefix + counter++)); } } - return formula.substitute(f, state); + return LNGResult.of(formula.substitute(f, state)); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/BDDNormalFormTransformation.java b/src/main/java/com/booleworks/logicng/transformations/BDDNormalFormTransformation.java index 44f85490..79a4fa74 100644 --- a/src/main/java/com/booleworks/logicng/transformations/BDDNormalFormTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/BDDNormalFormTransformation.java @@ -8,7 +8,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; -import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.knowledgecompilation.bdds.BDD; import com.booleworks.logicng.knowledgecompilation.bdds.BDDFactory; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; @@ -64,31 +65,37 @@ public BDDNormalFormTransformation(final FormulaFactory f, final boolean cnf, fi /** * Computes the CNF or DNF from the given formula by using a BDD. * @param formula the formula to transform - * @return the normal form (CNF or DNF) of the formula + * @param handler the computation handler + * @return a (potentially aborted) LNGResult with the normal form (CNF or + * DNF) of the formula */ - protected Formula compute(final Formula formula) { - if (formula.type().precedence() >= FType.LITERAL.precedence()) { - return formula; - } - if (hasNormalForm(formula, cnf)) { - return formula; + protected LNGResult compute(final Formula formula, final ComputationHandler handler) { + if (formula.type().precedence() >= FType.LITERAL.precedence() || hasNormalForm(formula, cnf)) { + return LNGResult.of(formula); } final Formula cached = lookupCache(formula); if (cached != null) { - return cached; + return LNGResult.of(cached); + } + final LNGResult bdd = BDDFactory.build(f, formula, state, handler); + if (!bdd.isSuccess()) { + return LNGResult.aborted(bdd.getAbortionEvent()); } - final BDD bdd = BDDFactory.build(f, formula, state, NopHandler.get()); - final Formula normalForm = cnf ? bdd.cnf() : bdd.dnf(); - final Formula simplifiedNormalForm; + final Formula normalForm = cnf ? bdd.getResult().cnf() : bdd.getResult().dnf(); + final LNGResult simplifiedNormalForm; final UnitPropagation up = new UnitPropagation(f); if (cnf) { - simplifiedNormalForm = normalForm.transform(up); + simplifiedNormalForm = normalForm.transform(up, handler); } else { // unit propagation simplification creates a CNF, so we use the // negated DNF to negate the result back to DNF again - simplifiedNormalForm = normalForm.negate(f).nnf(f).transform(up).negate(f).nnf(f); + simplifiedNormalForm = normalForm.negate(f).nnf(f) + .transform(up, handler) + .map(result -> result.negate(f).nnf(f)); + } + if (simplifiedNormalForm.isSuccess()) { + setCache(formula, simplifiedNormalForm.getResult()); } - setCache(formula, simplifiedNormalForm); return simplifiedNormalForm; } diff --git a/src/main/java/com/booleworks/logicng/transformations/CanonicalEnumeration.java b/src/main/java/com/booleworks/logicng/transformations/CanonicalEnumeration.java index 4ab4fd72..ad991120 100644 --- a/src/main/java/com/booleworks/logicng/transformations/CanonicalEnumeration.java +++ b/src/main/java/com/booleworks/logicng/transformations/CanonicalEnumeration.java @@ -8,6 +8,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.ModelEnumerationFunction; import com.booleworks.logicng.util.FormulaHelper; @@ -35,24 +37,32 @@ public CanonicalEnumeration(final FormulaFactory f) { * Constructs the canonical CNF/DNF of the given formula by enumerating the * falsifying/satisfying assignments. * @param formula the formula + * @param handler the computation handler * @param cnf {@code true} if the canonical CNF should be computed, * {@code false} if the canonical DNF should be computed - * @return the canonical normal form (CNF or DNF) of the formula + * @return the (potentially aborted) result with the canonical normal form + * (CNF or DNF) of the formula */ - protected Formula compute(final Formula formula, final boolean cnf) { + protected LNGResult compute(final Formula formula, final ComputationHandler handler, final boolean cnf) { final SATSolver solver = SATSolver.newSolver(f); solver.add(cnf ? formula.negate(f) : formula); - final List enumeration = solver.execute(ModelEnumerationFunction.builder(formula.variables(f)).build()); - if (enumeration.isEmpty()) { - return f.constant(cnf); + final LNGResult> enumerationResult = solver.execute( + ModelEnumerationFunction.builder(formula.variables(f)).build(), handler); + if (!enumerationResult.isSuccess()) { + return LNGResult.aborted(enumerationResult.getAbortionEvent()); + } else { + List enumeration = enumerationResult.getResult(); + if (enumeration.isEmpty()) { + return LNGResult.of(f.constant(cnf)); + } + final List ops = new ArrayList<>(); + for (final Model model : enumeration) { + final List literals = model.getLiterals(); + final Formula term = + cnf ? f.or(FormulaHelper.negate(f, literals, ArrayList::new)) : f.and(model.getLiterals()); + ops.add(term); + } + return LNGResult.of(cnf ? f.and(ops) : f.or(ops)); } - final List ops = new ArrayList<>(); - for (final Model model : enumeration) { - final List literals = model.getLiterals(); - final Formula term = - cnf ? f.or(FormulaHelper.negate(f, literals, ArrayList::new)) : f.and(model.getLiterals()); - ops.add(term); - } - return cnf ? f.and(ops) : f.or(ops); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/FormulaFactoryImporter.java b/src/main/java/com/booleworks/logicng/transformations/FormulaFactoryImporter.java index 4b02a95f..5a8d4dc4 100644 --- a/src/main/java/com/booleworks/logicng/transformations/FormulaFactoryImporter.java +++ b/src/main/java/com/booleworks/logicng/transformations/FormulaFactoryImporter.java @@ -14,6 +14,8 @@ import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.Or; import com.booleworks.logicng.formulas.PBConstraint; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -38,7 +40,11 @@ public FormulaFactoryImporter(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return LNGResult.of(applyRec(formula)); + } + + private Formula applyRec(final Formula formula) { if (formula.factory() == f) { return formula; } diff --git a/src/main/java/com/booleworks/logicng/transformations/LiteralSubstitution.java b/src/main/java/com/booleworks/logicng/transformations/LiteralSubstitution.java index cf3abfa6..f7bc38e2 100644 --- a/src/main/java/com/booleworks/logicng/transformations/LiteralSubstitution.java +++ b/src/main/java/com/booleworks/logicng/transformations/LiteralSubstitution.java @@ -10,6 +10,8 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.PBConstraint; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import java.util.ArrayList; import java.util.List; @@ -41,7 +43,11 @@ public LiteralSubstitution(final FormulaFactory f, final Map s } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return LNGResult.of(substitute(formula)); + } + + private Formula substitute(final Formula formula) { switch (formula.type()) { case TRUE: case FALSE: diff --git a/src/main/java/com/booleworks/logicng/transformations/NNFTransformation.java b/src/main/java/com/booleworks/logicng/transformations/NNFTransformation.java index 6513850d..97e8fb14 100644 --- a/src/main/java/com/booleworks/logicng/transformations/NNFTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/NNFTransformation.java @@ -12,6 +12,8 @@ import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.PBConstraint; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import java.util.Iterator; import java.util.LinkedHashSet; @@ -46,8 +48,8 @@ public NNFTransformation(final FormulaFactory f, final Map cac } @Override - public Formula apply(final Formula formula) { - return applyRec(formula, true); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return LNGResult.of(applyRec(formula, true)); } private Formula applyRec(final Formula formula, final boolean polarity) { diff --git a/src/main/java/com/booleworks/logicng/transformations/PureExpansionTransformation.java b/src/main/java/com/booleworks/logicng/transformations/PureExpansionTransformation.java index a4849046..09e55b84 100644 --- a/src/main/java/com/booleworks/logicng/transformations/PureExpansionTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/PureExpansionTransformation.java @@ -13,6 +13,8 @@ import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.PBConstraint; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.util.FormulaHelper; import java.util.ArrayList; @@ -34,7 +36,11 @@ public PureExpansionTransformation(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return LNGResult.of(expand(formula)); + } + + private Formula expand(final Formula formula) { switch (formula.type()) { case FALSE: case TRUE: diff --git a/src/main/java/com/booleworks/logicng/transformations/Subsumption.java b/src/main/java/com/booleworks/logicng/transformations/Subsumption.java index 47b28836..9b115a7d 100644 --- a/src/main/java/com/booleworks/logicng/transformations/Subsumption.java +++ b/src/main/java/com/booleworks/logicng/transformations/Subsumption.java @@ -4,10 +4,16 @@ package com.booleworks.logicng.transformations; +import static com.booleworks.logicng.handlers.events.SimpleEvent.SUBSUMPTION_ADDED_NEW_SET; +import static com.booleworks.logicng.handlers.events.SimpleEvent.SUBSUMPTION_STARTING_UB_TREE_GENERATION; + import com.booleworks.logicng.datastructures.ubtrees.UBTree; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.NopHandler; import java.util.ArrayList; import java.util.List; @@ -26,7 +32,7 @@ public abstract class Subsumption extends StatelessFormulaTransformation { /** * Constructor. * @param f the formula factory to generate new formulas - **/ + */ public Subsumption(final FormulaFactory f) { super(f); } @@ -38,18 +44,36 @@ public Subsumption(final FormulaFactory f) { * @return the UBTree with the operands and deleted subsumed operands */ protected UBTree generateSubsumedUBTree(final Formula formula) { + //noinspection OptionalGetWithoutIsPresent + return generateSubsumedUBTree(formula, NopHandler.get()).getResult(); + } + + /** + * Generates a UBTree from the formulas operands (clauses in CNF, minterms + * in DNF) where all subsumed operands are already deleted. + * @param formula the formula (must be an n-ary operator and CNF or DNF) + * @param handler the computation handler + * @return the UBTree with the operands and deleted subsumed operands + */ + protected LNGResult> generateSubsumedUBTree(final Formula formula, final ComputationHandler handler) { final SortedMap>> mapping = new TreeMap<>(); for (final Formula term : formula) { mapping.computeIfAbsent(term.literals(f).size(), k -> new ArrayList<>()).add(term.literals(f)); } + if (!handler.shouldResume(SUBSUMPTION_STARTING_UB_TREE_GENERATION)) { + return LNGResult.aborted(SUBSUMPTION_STARTING_UB_TREE_GENERATION); + } final UBTree ubTree = new UBTree<>(); for (final Map.Entry>> entry : mapping.entrySet()) { for (final SortedSet set : entry.getValue()) { if (ubTree.firstSubset(set) == null) { ubTree.addSet(set); + if (!handler.shouldResume(SUBSUMPTION_ADDED_NEW_SET)) { + return LNGResult.aborted(SUBSUMPTION_ADDED_NEW_SET); + } } } } - return ubTree; + return LNGResult.of(ubTree); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/UnitPropagation.java b/src/main/java/com/booleworks/logicng/transformations/UnitPropagation.java index 7ff005fe..296a4820 100644 --- a/src/main/java/com/booleworks/logicng/transformations/UnitPropagation.java +++ b/src/main/java/com/booleworks/logicng/transformations/UnitPropagation.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.datastructures.LNGClause; import com.booleworks.logicng.solvers.sat.LNGCoreSolver; import com.booleworks.logicng.solvers.sat.SATSolverConfig; @@ -45,16 +47,16 @@ public UnitPropagation(final FormulaFactory f, final Map cache } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { final Formula cached = lookupCache(formula); if (cached != null) { - return cached; + return LNGResult.of(cached); } final Propagator propagator = new Propagator(f); propagator.add(formula); final Formula result = propagator.propagatedFormula(f); setCache(formula, result); - return result; + return LNGResult.of(result); } /** diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/BDDCNFTransformation.java b/src/main/java/com/booleworks/logicng/transformations/cnf/BDDCNFTransformation.java index 5284b5e2..c553cd83 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/BDDCNFTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/BDDCNFTransformation.java @@ -6,6 +6,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; import com.booleworks.logicng.transformations.BDDNormalFormTransformation; @@ -57,7 +59,7 @@ public BDDCNFTransformation(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { - return compute(formula); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return compute(formula, handler); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFEncoder.java b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFEncoder.java index c41f7a77..bd5cd8de 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFEncoder.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFEncoder.java @@ -15,8 +15,9 @@ import com.booleworks.logicng.formulas.FormulaTransformation; import com.booleworks.logicng.formulas.implementation.cached.CachingFormulaFactory; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.events.FactorizationCreatedClauseEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import java.util.ArrayList; import java.util.List; @@ -76,7 +77,7 @@ public static Formula encode(final FormulaFactory f, final Formula formula, fina protected static Formula advancedEncoding(final FormulaFactory f, final Formula formula, final CNFConfig config) { final var factorizationHandler = new AdvancedFactorizationHandler(); factorizationHandler.setBounds(config.distributionBoundary, config.createdClauseBoundary); - final var advancedFactorization = new CNFFactorization(f, factorizationHandler); + final var advancedFactorization = new CNFFactorization(f); final FormulaTransformation fallbackTransformation; switch (config.fallbackAlgorithmForAdvancedEncoding) { case TSEITIN: @@ -92,20 +93,23 @@ protected static Formula advancedEncoding(final FormulaFactory f, final Formula if (formula.type() == FType.AND) { final List operands = new ArrayList<>(formula.numberOfOperands()); for (final Formula op : formula) { - operands.add(singleAdvancedEncoding(op, advancedFactorization, fallbackTransformation)); + operands.add(singleAdvancedEncoding(op, advancedFactorization, factorizationHandler, fallbackTransformation)); } return f.and(operands); } - return singleAdvancedEncoding(formula, advancedFactorization, fallbackTransformation); + return singleAdvancedEncoding(formula, advancedFactorization, factorizationHandler, fallbackTransformation); } - protected static Formula singleAdvancedEncoding(final Formula formula, final CNFFactorization advancedFactorization, + protected static Formula singleAdvancedEncoding(final Formula formula, + final CNFFactorization advancedFactorization, + final AdvancedFactorizationHandler factorizationHandler, final FormulaTransformation fallback) { - Formula result = formula.transform(advancedFactorization); - if (result == null) { - result = formula.transform(fallback); + final LNGResult result = formula.transform(advancedFactorization, factorizationHandler); + if (result.isSuccess()) { + return result.getResult(); + } else { + return formula.transform(fallback); } - return result; } private static FormulaTransformation getTseitinTransformation(final FormulaFactory f, final CNFConfig config) { @@ -141,7 +145,7 @@ protected void setBounds(final int distributionBoundary, final int createdClause } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == FACTORIZATION_STARTED) { currentDistributions = 0; currentClauses = 0; @@ -152,10 +156,5 @@ public boolean shouldResume(final LogicNGEvent event) { } return !aborted; } - - @Override - public boolean isAborted() { - return aborted; - } } } diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFFactorization.java b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFFactorization.java index a24ba2d1..62d566ce 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFFactorization.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFFactorization.java @@ -12,9 +12,9 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.events.FactorizationCreatedClauseEvent; -import com.booleworks.logicng.transformations.CacheableAndAbortableFormulaTransformation; +import com.booleworks.logicng.transformations.CacheableFormulaTransformation; import java.util.Iterator; import java.util.LinkedHashSet; @@ -25,141 +25,127 @@ * @version 3.0.0 * @since 1.0 */ -public final class CNFFactorization extends CacheableAndAbortableFormulaTransformation { - - private boolean proceed = true; +public final class CNFFactorization extends CacheableFormulaTransformation { /** * Constructor for a CNF Factorization. * @param f the formula factory to generate new formulas */ public CNFFactorization(final FormulaFactory f) { - super(f, TransformationCacheEntry.FACTORIZED_CNF, NopHandler.get()); + super(f, TransformationCacheEntry.FACTORIZED_CNF); } /** - * Constructor for a CNF Factorization. + * Constructor for a CNF Factorization. For all factory type the provided + * cache will be used. If it is null, no cache will be used. * @param f the formula factory to generate new formulas * @param cache the cache to use for the transformation */ public CNFFactorization(final FormulaFactory f, final Map cache) { - this(f, NopHandler.get(), cache); - } - - /** - * Constructor for a CNF Factorization. - * @param f the formula factory to generate new formulas - * @param handler the handler for the transformation - */ - public CNFFactorization(final FormulaFactory f, final ComputationHandler handler) { - super(f, TransformationCacheEntry.FACTORIZED_CNF, handler); - } - - /** - * Constructs a new transformation. For all factory type the provided cache - * will be used. If it is null, no cache will be used. The handler - if not - * null - is used for aborting the computation. - * @param f the formula factory to generate new formulas - * @param cache the cache to use for the transformation - * @param handler the handler for the transformation - */ - public CNFFactorization(final FormulaFactory f, final ComputationHandler handler, - final Map cache) { - super(f, cache, handler); + super(f, cache); } @Override - public Formula apply(final Formula formula) { - proceed = handler.shouldResume(FACTORIZATION_STARTED); - return applyRec(formula); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + if (!handler.shouldResume(FACTORIZATION_STARTED)) { + return LNGResult.aborted(FACTORIZATION_STARTED); + } + return applyRec(formula, handler); } - private Formula applyRec(final Formula formula) { - if (!proceed) { - return null; - } + private LNGResult applyRec(final Formula formula, final ComputationHandler handler) { if (formula.type().precedence() >= FType.LITERAL.precedence()) { - return formula; + return LNGResult.of(formula); } - Formula cached = lookupCache(formula); + final Formula cached = lookupCache(formula); if (cached != null) { - return cached; + return LNGResult.of(cached); } + final Formula computed; switch (formula.type()) { case NOT: case IMPL: case EQUIV: - cached = applyRec(formula.nnf(f)); + final LNGResult rec = applyRec(formula.nnf(f), handler); + if (rec.isSuccess()) { + computed = rec.getResult(); + } else { + return rec; + } break; case OR: LinkedHashSet nops = new LinkedHashSet<>(); for (final Formula op : formula) { - if (!proceed) { - return null; + final LNGResult nop = applyRec(op, handler); + if (nop.isSuccess()) { + nops.add(nop.getResult()); + } else { + return nop; } - nops.add(applyRec(op)); } final Iterator it = nops.iterator(); - cached = it.next(); + Formula currentResult = it.next(); while (it.hasNext()) { - if (!proceed) { - return null; + final LNGResult distributed = distribute(currentResult, it.next(), handler); + if (distributed.isSuccess()) { + currentResult = distributed.getResult(); + } else { + return distributed; } - cached = distribute(cached, it.next()); } + computed = currentResult; break; case AND: nops = new LinkedHashSet<>(); for (final Formula op : formula) { - final Formula apply = applyRec(op); - if (!proceed) { - return null; + final LNGResult nop = applyRec(op, handler); + if (nop.isSuccess()) { + nops.add(nop.getResult()); + } else { + return nop; } - nops.add(apply); } - cached = f.and(nops); + computed = f.and(nops); break; case PBC: - cached = formula.nnf(f); + computed = formula.nnf(f); break; default: throw new IllegalArgumentException("Could not process the formula type " + formula.type()); } - if (proceed) { - setCache(formula, cached); - return cached; - } - return null; + setCache(formula, computed); + return LNGResult.of(computed); } /** * Computes the distribution (factorization) of two formulas. - * @param f1 the first formula - * @param f2 the second formula + * @param f1 the first formula + * @param f2 the second formula + * @param handler the computation handler * @return the distribution of the two formulas */ - private Formula distribute(final Formula f1, final Formula f2) { - if (handler != null) { - proceed = handler.shouldResume(DISTRIBUTION_PERFORMED); + private LNGResult distribute(final Formula f1, final Formula f2, final ComputationHandler handler) { + if (!handler.shouldResume(DISTRIBUTION_PERFORMED)) { + return LNGResult.aborted(DISTRIBUTION_PERFORMED); } - if (proceed) { - if (f1.type() == FType.AND || f2.type() == FType.AND) { - final LinkedHashSet nops = new LinkedHashSet<>(); - for (final Formula op : f1.type() == FType.AND ? f1 : f2) { - final Formula distribute = distribute(op, f1.type() == FType.AND ? f2 : f1); - if (!proceed) { - return null; - } - nops.add(distribute); + if (f1.type() == FType.AND || f2.type() == FType.AND) { + final LinkedHashSet nops = new LinkedHashSet<>(); + for (final Formula op : f1.type() == FType.AND ? f1 : f2) { + final LNGResult distributed = distribute(op, f1.type() == FType.AND ? f2 : f1, handler); + if (distributed.isSuccess()) { + nops.add(distributed.getResult()); + } else { + return distributed; } - return f.and(nops); } - final Formula clause = f.or(f1, f2); - if (handler != null) { - proceed = handler.shouldResume(new FactorizationCreatedClauseEvent(clause)); - } - return clause; + return LNGResult.of(f.and(nops)); + } + final Formula clause = f.or(f1, f2); + final FactorizationCreatedClauseEvent createdClauseEvent = new FactorizationCreatedClauseEvent(clause); + if (handler.shouldResume(createdClauseEvent)) { + return LNGResult.of(clause); + } else { + return LNGResult.aborted(createdClauseEvent); } - return null; } } diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFSubsumption.java b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFSubsumption.java index c4e7e473..7413a123 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/CNFSubsumption.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/CNFSubsumption.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.Subsumption; import java.util.ArrayList; @@ -29,20 +31,29 @@ public CNFSubsumption(final FormulaFactory f) { super(f); } + public CNFSubsumption(final FormulaFactory f, final ComputationHandler handler) { + super(f); + } + @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { if (!formula.isCNF(f)) { throw new IllegalArgumentException("CNF subsumption can only be applied to formulas in CNF"); } if (formula.type().precedence() >= FType.LITERAL.precedence() || formula.type() == FType.OR) { - return formula; + return LNGResult.of(formula); } assert formula.type() == FType.AND; - final UBTree ubTree = generateSubsumedUBTree(formula); - final List clauses = new ArrayList<>(); - for (final SortedSet literals : ubTree.allSets()) { - clauses.add(f.clause(literals)); + final LNGResult> ubTreeResult = generateSubsumedUBTree(formula, handler); + if (!ubTreeResult.isSuccess()) { + return LNGResult.aborted(ubTreeResult.getAbortionEvent()); + } else { + final UBTree ubTree = ubTreeResult.getResult(); + final List clauses = new ArrayList<>(); + for (final SortedSet literals : ubTree.allSets()) { + clauses.add(f.clause(literals)); + } + return LNGResult.of(f.cnf(clauses)); } - return f.cnf(clauses); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/CanonicalCNFEnumeration.java b/src/main/java/com/booleworks/logicng/transformations/cnf/CanonicalCNFEnumeration.java index aa16c239..4786041f 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/CanonicalCNFEnumeration.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/CanonicalCNFEnumeration.java @@ -6,6 +6,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.CanonicalEnumeration; /** @@ -21,7 +23,7 @@ public CanonicalCNFEnumeration(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { - return compute(formula, true); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + return compute(formula, handler, true); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTransformation.java b/src/main/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTransformation.java index 7ce74323..2b782dd4 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTransformation.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatefulFormulaTransformation; import java.util.ArrayList; @@ -104,10 +106,10 @@ private Literal pgVariable(final Formula formula) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { final Formula nnf = formula.nnf(f); if (nnf.isCNF(f)) { - return nnf; + return LNGResult.of(nnf); } Formula pg; if (nnf.numberOfAtoms(f) < boundaryForFactorization) { @@ -118,7 +120,7 @@ public Formula apply(final Formula formula) { pg = pg.restrict(f, topLevel); } state.literalMap.put(formula, state.literal(nnf)); - return pg; + return LNGResult.of(pg); } private Formula computeTransformation(final Formula formula) { diff --git a/src/main/java/com/booleworks/logicng/transformations/cnf/TseitinTransformation.java b/src/main/java/com/booleworks/logicng/transformations/cnf/TseitinTransformation.java index 1e0b667b..f186197d 100644 --- a/src/main/java/com/booleworks/logicng/transformations/cnf/TseitinTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/cnf/TseitinTransformation.java @@ -10,6 +10,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatefulFormulaTransformation; import java.util.ArrayList; @@ -86,15 +88,15 @@ protected TseitinState inititialState() { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { final Formula nnf = formula.nnf(f); if (nnf.isCNF(f)) { - return nnf; + return LNGResult.of(nnf); } Formula tseitin = state.formula(nnf); if (tseitin != null) { final Assignment topLevel = new Assignment(state.literal(nnf)); - return state.formula(nnf).restrict(f, topLevel); + return LNGResult.of(state.formula(nnf).restrict(f, topLevel)); } if (nnf.numberOfAtoms(f) < boundaryForFactorization) { tseitin = nnf.transform(factorization); @@ -106,7 +108,7 @@ public Formula apply(final Formula formula) { tseitin = state.formula(nnf).restrict(f, topLevel); } state.literalMap.put(formula, state.literal(nnf)); - return tseitin; + return LNGResult.of(tseitin); } /** diff --git a/src/main/java/com/booleworks/logicng/transformations/dnf/BDDDNFTransformation.java b/src/main/java/com/booleworks/logicng/transformations/dnf/BDDDNFTransformation.java index 31e18aa1..3b247ef3 100644 --- a/src/main/java/com/booleworks/logicng/transformations/dnf/BDDDNFTransformation.java +++ b/src/main/java/com/booleworks/logicng/transformations/dnf/BDDDNFTransformation.java @@ -6,6 +6,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; import com.booleworks.logicng.transformations.BDDNormalFormTransformation; @@ -57,7 +59,7 @@ public BDDDNFTransformation(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { - return compute(formula); + public LNGResult apply(final Formula formula, ComputationHandler handler) { + return compute(formula, handler); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/dnf/CanonicalDNFEnumeration.java b/src/main/java/com/booleworks/logicng/transformations/dnf/CanonicalDNFEnumeration.java index dcc66d6c..0dede2a5 100644 --- a/src/main/java/com/booleworks/logicng/transformations/dnf/CanonicalDNFEnumeration.java +++ b/src/main/java/com/booleworks/logicng/transformations/dnf/CanonicalDNFEnumeration.java @@ -6,6 +6,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.CanonicalEnumeration; /** @@ -20,7 +22,7 @@ public CanonicalDNFEnumeration(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { - return compute(formula, false); + public LNGResult apply(final Formula formula, ComputationHandler handler) { + return compute(formula, handler, false); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/dnf/DNFFactorization.java b/src/main/java/com/booleworks/logicng/transformations/dnf/DNFFactorization.java index d2b369b7..1c22d119 100644 --- a/src/main/java/com/booleworks/logicng/transformations/dnf/DNFFactorization.java +++ b/src/main/java/com/booleworks/logicng/transformations/dnf/DNFFactorization.java @@ -12,9 +12,9 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.events.FactorizationCreatedClauseEvent; -import com.booleworks.logicng.transformations.CacheableAndAbortableFormulaTransformation; +import com.booleworks.logicng.transformations.CacheableFormulaTransformation; import java.util.Iterator; import java.util.LinkedHashSet; @@ -25,16 +25,14 @@ * @version 3.0.0 * @since 1.0 */ -public final class DNFFactorization extends CacheableAndAbortableFormulaTransformation { - - private boolean proceed = true; +public final class DNFFactorization extends CacheableFormulaTransformation { /** * Constructor for a DNF Factorization. * @param f the formula factory to generate new formulas */ public DNFFactorization(final FormulaFactory f) { - super(f, TransformationCacheEntry.FACTORIZED_DNF, NopHandler.get()); + super(f, TransformationCacheEntry.FACTORIZED_DNF); } /** @@ -43,122 +41,108 @@ public DNFFactorization(final FormulaFactory f) { * @param cache the cache to use for the transformation */ public DNFFactorization(final FormulaFactory f, final Map cache) { - this(f, NopHandler.get(), cache); - } - - /** - * Constructor for a DNF Factorization. - * @param f the formula factory to generate new formulas - * @param handler the handler for the transformation - */ - public DNFFactorization(final FormulaFactory f, final ComputationHandler handler) { - super(f, TransformationCacheEntry.FACTORIZED_DNF, handler); - } - - /** - * Constructs a new transformation. For all factory type the provided cache - * will be used. If it is null, no cache will be used. The handler - if not - * null - is used for aborting the computation. - * @param f the formula factory to generate new formulas - * @param cache the cache to use for the transformation - * @param handler the handler for the transformation - */ - public DNFFactorization(final FormulaFactory f, final ComputationHandler handler, - final Map cache) { - super(f, cache, handler); + super(f, cache); } @Override - public Formula apply(final Formula formula) { - handler.shouldResume(FACTORIZATION_STARTED); - proceed = true; - return applyRec(formula); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + if (!handler.shouldResume(FACTORIZATION_STARTED)) { + return LNGResult.aborted(FACTORIZATION_STARTED); + } + return applyRec(formula, handler); } - private Formula applyRec(final Formula formula) { - if (!proceed) { - return null; - } + private LNGResult applyRec(final Formula formula, final ComputationHandler handler) { if (formula.type().precedence() >= FType.LITERAL.precedence()) { - return formula; + return LNGResult.of(formula); } - Formula cached = lookupCache(formula); + final Formula cached = lookupCache(formula); if (cached != null) { - return cached; + return LNGResult.of(cached); } + final Formula computed; switch (formula.type()) { case NOT: case IMPL: case EQUIV: case PBC: - cached = applyRec(formula.nnf(f)); + final LNGResult rec = applyRec(formula.nnf(f), handler); + if (rec.isSuccess()) { + computed = rec.getResult(); + } else { + return rec; + } break; case OR: LinkedHashSet nops = new LinkedHashSet<>(); for (final Formula op : formula) { - final Formula apply = applyRec(op); - if (!proceed) { - return null; + final LNGResult nop = applyRec(op, handler); + if (nop.isSuccess()) { + nops.add(nop.getResult()); + } else { + return nop; } - nops.add(apply); } - cached = f.or(nops); + computed = f.or(nops); break; case AND: nops = new LinkedHashSet<>(); for (final Formula op : formula) { - if (!proceed) { - return null; + final LNGResult nop = applyRec(op, handler); + if (nop.isSuccess()) { + nops.add(nop.getResult()); + } else { + return nop; } - nops.add(applyRec(op)); } final Iterator it = nops.iterator(); - cached = it.next(); + Formula currentResult = it.next(); while (it.hasNext()) { - if (!proceed) { - return null; + final LNGResult distributed = distribute(currentResult, it.next(), handler); + if (distributed.isSuccess()) { + currentResult = distributed.getResult(); + } else { + return distributed; } - cached = distribute(cached, it.next()); } + computed = currentResult; break; default: throw new IllegalArgumentException("Could not process the formula type " + formula.type()); } - if (proceed) { - setCache(formula, cached); - return cached; - } - return null; + setCache(formula, computed); + return LNGResult.of(computed); } /** * Computes the distribution (factorization) of two formulas. - * @param f1 the first formula - * @param f2 the second formula + * @param f1 the first formula + * @param f2 the second formula + * @param handler the computation handler * @return the distribution of the two formulas */ - private Formula distribute(final Formula f1, final Formula f2) { - if (handler != null) { - proceed = handler.shouldResume(DISTRIBUTION_PERFORMED); + private LNGResult distribute(final Formula f1, final Formula f2, final ComputationHandler handler) { + if (!handler.shouldResume(DISTRIBUTION_PERFORMED)) { + return LNGResult.aborted(DISTRIBUTION_PERFORMED); } - if (proceed) { - if (f1.type() == FType.OR || f2.type() == FType.OR) { - final LinkedHashSet nops = new LinkedHashSet<>(); - for (final Formula op : f1.type() == FType.OR ? f1 : f2) { - final Formula distribute = distribute(op, f1.type() == FType.OR ? f2 : f1); - if (!proceed) { - return null; - } - nops.add(distribute); + if (f1.type() == FType.OR || f2.type() == FType.OR) { + final LinkedHashSet nops = new LinkedHashSet<>(); + for (final Formula op : f1.type() == FType.OR ? f1 : f2) { + final LNGResult distributed = distribute(op, f1.type() == FType.OR ? f2 : f1, handler); + if (distributed.isSuccess()) { + nops.add(distributed.getResult()); + } else { + return distributed; } - return f.or(nops); } - final Formula clause = f.and(f1, f2); - if (handler != null) { - proceed = handler.shouldResume(new FactorizationCreatedClauseEvent(clause)); - } - return clause; + return LNGResult.of(f.or(nops)); + } + final Formula clause = f.and(f1, f2); + final FactorizationCreatedClauseEvent createdClauseEvent = new FactorizationCreatedClauseEvent(clause); + if (handler.shouldResume(createdClauseEvent)) { + return LNGResult.of(clause); + } else { + return LNGResult.aborted(createdClauseEvent); } - return null; } } diff --git a/src/main/java/com/booleworks/logicng/transformations/dnf/DNFSubsumption.java b/src/main/java/com/booleworks/logicng/transformations/dnf/DNFSubsumption.java index ba919fd6..32f1c137 100644 --- a/src/main/java/com/booleworks/logicng/transformations/dnf/DNFSubsumption.java +++ b/src/main/java/com/booleworks/logicng/transformations/dnf/DNFSubsumption.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.Subsumption; import java.util.ArrayList; @@ -30,19 +32,24 @@ public DNFSubsumption(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { if (!formula.isDNF(f)) { throw new IllegalArgumentException("DNF subsumption can only be applied to formulas in DNF"); } if (formula.type().precedence() >= FType.LITERAL.precedence() || formula.type() == FType.AND) { - return formula; + return LNGResult.of(formula); } assert formula.type() == FType.OR; - final UBTree ubTree = generateSubsumedUBTree(formula); - final List minterms = new ArrayList<>(); - for (final SortedSet literals : ubTree.allSets()) { - minterms.add(f.and(literals)); + final LNGResult> ubTreeResult = generateSubsumedUBTree(formula, handler); + if (!ubTreeResult.isSuccess()) { + return LNGResult.aborted(ubTreeResult.getAbortionEvent()); + } else { + final UBTree ubTree = ubTreeResult.getResult(); + final List minterms = new ArrayList<>(); + for (final SortedSet literals : ubTree.allSets()) { + minterms.add(f.and(literals)); + } + return LNGResult.of(f.or(minterms)); } - return f.or(minterms); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/qe/ExistentialQuantifierElimination.java b/src/main/java/com/booleworks/logicng/transformations/qe/ExistentialQuantifierElimination.java index 5c77cc10..e3e70b82 100644 --- a/src/main/java/com/booleworks/logicng/transformations/qe/ExistentialQuantifierElimination.java +++ b/src/main/java/com/booleworks/logicng/transformations/qe/ExistentialQuantifierElimination.java @@ -8,6 +8,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatelessFormulaTransformation; import java.util.Arrays; @@ -50,11 +52,11 @@ public ExistentialQuantifierElimination(final FormulaFactory f, final Collection } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, ComputationHandler handler) { Formula result = formula; for (final Variable var : elimination) { result = f.or(result.restrict(f, new Assignment(var)), result.restrict(f, new Assignment(var.negate(f)))); } - return result; + return LNGResult.of(result); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/qe/UniversalQuantifierElimination.java b/src/main/java/com/booleworks/logicng/transformations/qe/UniversalQuantifierElimination.java index 82b396ba..6bba3daf 100644 --- a/src/main/java/com/booleworks/logicng/transformations/qe/UniversalQuantifierElimination.java +++ b/src/main/java/com/booleworks/logicng/transformations/qe/UniversalQuantifierElimination.java @@ -8,6 +8,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatelessFormulaTransformation; import java.util.Arrays; @@ -50,11 +52,11 @@ public UniversalQuantifierElimination(final FormulaFactory f, final Collection apply(final Formula formula, ComputationHandler handler) { Formula result = formula; for (final Variable var : elimination) { result = f.and(result.restrict(f, new Assignment(var)), result.restrict(f, new Assignment(var.negate(f)))); } - return result; + return LNGResult.of(result); } } diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifier.java index 160eb9a8..58e40b82 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifier.java @@ -5,7 +5,6 @@ package com.booleworks.logicng.transformations.simplification; import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.ADVANCED_SIMPLIFICATION_STARTED; -import static com.booleworks.logicng.handlers.events.SimpleEvent.NO_EVENT; import com.booleworks.logicng.backbones.Backbone; import com.booleworks.logicng.backbones.BackboneGeneration; @@ -17,10 +16,11 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.UnsatResult; import com.booleworks.logicng.primecomputation.PrimeCompiler; import com.booleworks.logicng.primecomputation.PrimeResult; -import com.booleworks.logicng.transformations.AbortableFormulaTransformation; +import com.booleworks.logicng.transformations.StatelessFormulaTransformation; import com.booleworks.logicng.util.FormulaHelper; import java.util.ArrayList; @@ -56,7 +56,7 @@ * @version 3.0.0 * @since 2.0.0 */ -public final class AdvancedSimplifier extends AbortableFormulaTransformation { +public final class AdvancedSimplifier extends StatelessFormulaTransformation { private final AdvancedSimplifierConfig config; @@ -66,66 +66,46 @@ public final class AdvancedSimplifier extends AbortableFormulaTransformation { * @param f the formula factory to generate new formulas */ public AdvancedSimplifier(final FormulaFactory f) { - this(f, (AdvancedSimplifierConfig) f.configurationFor(ConfigurationType.ADVANCED_SIMPLIFIER), NopHandler.get()); - } - - /** - * Constructs a new simplifier with the advanced simplifier configuration - * from the formula factory. - * @param f the formula factory to generate new formulas - * @param handler the optimization handler to abort the simplification - */ - public AdvancedSimplifier(final FormulaFactory f, final ComputationHandler handler) { - this(f, (AdvancedSimplifierConfig) f.configurationFor(ConfigurationType.ADVANCED_SIMPLIFIER), handler); + this(f, (AdvancedSimplifierConfig) f.configurationFor(ConfigurationType.ADVANCED_SIMPLIFIER)); } /** * Constructs a new simplifier with the given configuration. * @param f the formula factory to generate new formulas * @param config The configuration for the advanced simplifier, including a - * handler, a rating function and flags for which steps should - * pe performed during the computation. + * handler, a rating function and flags for which steps + * should pe performed during the computation. */ public AdvancedSimplifier(final FormulaFactory f, final AdvancedSimplifierConfig config) { - this(f, config, NopHandler.get()); - } - - /** - * Constructs a new simplifier with the given configuration. - * @param f the formula factory to generate new formulas - * @param handler the optimization handler to abort the simplification - * @param config The configuration for the advanced simplifier, including a - * handler, a rating function and flags for which steps - * should pe performed during the computation. - */ - public AdvancedSimplifier(final FormulaFactory f, final AdvancedSimplifierConfig config, - final ComputationHandler handler) { - super(f, handler); + super(f); this.config = config; } @Override - public Formula apply(final Formula formula) { - handler.shouldResume(ADVANCED_SIMPLIFICATION_STARTED); + public LNGResult apply(final Formula formula, final ComputationHandler handler) { + if (!handler.shouldResume(ADVANCED_SIMPLIFICATION_STARTED)) { + return LNGResult.aborted(ADVANCED_SIMPLIFICATION_STARTED); + } Formula simplified = formula; final SortedSet backboneLiterals = new TreeSet<>(); if (config.restrictBackbone) { - final Backbone backbone = BackboneGeneration.compute(f, Collections.singletonList(formula), + final LNGResult backboneResult = BackboneGeneration.compute(f, Collections.singletonList(formula), formula.variables(f), BackboneType.POSITIVE_AND_NEGATIVE, handler); - if (backbone == null || !handler.shouldResume(NO_EVENT)) { - return null; + if (!backboneResult.isSuccess()) { + return LNGResult.aborted(backboneResult.getAbortionEvent()); } + final Backbone backbone = backboneResult.getResult(); if (!backbone.isSat()) { - return f.falsum(); + return LNGResult.of(f.falsum()); } backboneLiterals.addAll(backbone.getCompleteBackbone(f)); simplified = formula.restrict(f, new Assignment(backboneLiterals)); } - final Formula simplifyMinDnf = computeMinDnf(f, simplified); - if (simplifyMinDnf == null) { - return null; + final LNGResult simplifyMinDnf = computeMinDnf(f, simplified, handler); + if (!simplifyMinDnf.isSuccess()) { + return LNGResult.aborted(simplifyMinDnf.getAbortionEvent()); } - simplified = simplifyWithRating(simplified, simplifyMinDnf, config); + simplified = simplifyWithRating(simplified, simplifyMinDnf.getResult(), config); if (config.factorOut) { final Formula factoredOut = simplified.transform(new FactorOutSimplifier(f, config.ratingFunction)); simplified = simplifyWithRating(simplified, factoredOut, config); @@ -137,26 +117,29 @@ public Formula apply(final Formula formula) { final Formula negationSimplified = simplified.transform(new NegationSimplifier(f)); simplified = simplifyWithRating(simplified, negationSimplified, config); } - return simplified; + return LNGResult.of(simplified); } - private Formula computeMinDnf(final FormulaFactory f, Formula simplified) { - final PrimeResult primeResult = - PrimeCompiler.getWithMinimization().compute(f, simplified, PrimeResult.CoverageType.IMPLICANTS_COMPLETE, - handler); - if (primeResult == null || !handler.shouldResume(NO_EVENT)) { - return null; + private LNGResult computeMinDnf(final FormulaFactory f, final Formula simplified, + final ComputationHandler handler) { + final LNGResult primeResult = PrimeCompiler.getWithMinimization() + .compute(f, simplified, PrimeResult.CoverageType.IMPLICANTS_COMPLETE, handler); + if (!primeResult.isSuccess()) { + return LNGResult.aborted(primeResult.getAbortionEvent()); } - final List> primeImplicants = primeResult.getPrimeImplicants(); - final List minimizedPIs = + final List> primeImplicants = primeResult.getResult().getPrimeImplicants(); + final LNGResult>> minimizedPIsResult = SmusComputation.computeSmusForFormulas(f, negateAllLiterals(f, primeImplicants), Collections.singletonList(simplified), handler); - if (minimizedPIs == null || !handler.shouldResume(NO_EVENT)) { - return null; + if (!minimizedPIsResult.isSuccess()) { + return LNGResult.aborted(minimizedPIsResult.getAbortionEvent()); + } else if (!minimizedPIsResult.getResult().isUnsat()) { + return LNGResult.of(f.falsum()); + } else { + final List minimizedPIs = minimizedPIsResult.getResult().getResult(); + return LNGResult.of(f.or( + negateAllLiteralsInFormulas(f, minimizedPIs).stream().map(f::and).collect(Collectors.toList()))); } - simplified = - f.or(negateAllLiteralsInFormulas(f, minimizedPIs).stream().map(f::and).collect(Collectors.toList())); - return simplified; } private List negateAllLiterals(final FormulaFactory f, final Collection> literalSets) { diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifier.java index aea08aa5..98b18d32 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifier.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.datastructures.Assignment; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.BackboneFunction; import com.booleworks.logicng.transformations.StatelessFormulaTransformation; @@ -28,21 +30,27 @@ public BackboneSimplifier(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { final SATSolver solver = SATSolver.newSolver(f); solver.add(formula); - final Backbone backbone = solver.execute(BackboneFunction.builder().variables(formula.variables(f)) - .type(BackboneType.POSITIVE_AND_NEGATIVE).build()); + final LNGResult backboneResult = solver.execute(BackboneFunction.builder() + .variables(formula.variables(f)) + .type(BackboneType.POSITIVE_AND_NEGATIVE) + .build(), handler); + if (!backboneResult.isSuccess()) { + return LNGResult.aborted(backboneResult.getAbortionEvent()); + } + final Backbone backbone = backboneResult.getResult(); if (!backbone.isSat()) { - return f.falsum(); + return LNGResult.of(f.falsum()); } if (!backbone.getNegativeBackbone().isEmpty() || !backbone.getPositiveBackbone().isEmpty()) { final Formula backboneFormula = backbone.toFormula(f); final Assignment assignment = new Assignment(backbone.getCompleteBackbone(f)); final Formula restrictedFormula = formula.restrict(f, assignment); - return f.and(backboneFormula, restrictedFormula); + return LNGResult.of(f.and(backboneFormula, restrictedFormula)); } else { - return formula; + return LNGResult.of(formula); } } } diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifier.java index c53f0a4c..6c10c426 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifier.java @@ -11,6 +11,8 @@ import com.booleworks.logicng.formulas.Implication; import com.booleworks.logicng.formulas.Not; import com.booleworks.logicng.formulas.cache.TransformationCacheEntry; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.CacheableFormulaTransformation; import java.util.LinkedHashMap; @@ -35,10 +37,10 @@ public DistributiveSimplifier(final FormulaFactory f, final Map apply(final Formula formula, final ComputationHandler handler) { Formula result = lookupCache(formula); if (result != null) { - return result; + return LNGResult.of(result); } switch (formula.type()) { case FALSE: @@ -68,7 +70,7 @@ public Formula apply(final Formula formula) { throw new IllegalStateException("Unknown formula type: " + formula.type()); } setCache(formula, result); - return result; + return LNGResult.of(result); } private Formula distributeNAry(final Formula formula) { diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/FactorOutSimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/FactorOutSimplifier.java index ce55622f..552ba1b2 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/FactorOutSimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/FactorOutSimplifier.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.NAryOperator; import com.booleworks.logicng.formulas.Not; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatelessFormulaTransformation; import com.booleworks.logicng.util.Pair; @@ -50,14 +52,14 @@ public FactorOutSimplifier(final FormulaFactory f, final RatingFunction apply(final Formula formula, final ComputationHandler handler) { Formula last; Formula simplified = formula; do { last = simplified; simplified = applyRec(last); } while (!simplified.equals(last)); - return simplified; + return LNGResult.of(simplified); } private Formula applyRec(final Formula formula) { @@ -89,7 +91,7 @@ private Formula simplify(final NAryOperator formula) { final Formula simplified = factorOut(formula); return simplified == null || ratingFunction.apply(formula).doubleValue() <= ratingFunction.apply(simplified).doubleValue() ? formula - : simplified; + : simplified; } private Formula factorOut(final NAryOperator formula) { diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/NegationSimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/NegationSimplifier.java index d5322645..230e5fac 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/NegationSimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/NegationSimplifier.java @@ -9,6 +9,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.NAryOperator; +import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.transformations.StatelessFormulaTransformation; import java.util.ArrayList; @@ -31,13 +33,13 @@ public NegationSimplifier(final FormulaFactory f) { } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, final ComputationHandler handler) { final Formula nnf = formula.nnf(f); if (nnf.isAtomicFormula()) { - return getSmallestFormula(true, formula, nnf); + return LNGResult.of(getSmallestFormula(true, formula, nnf)); } final MinimizationResult result = minimize(nnf, true); - return getSmallestFormula(true, formula, nnf, result.positiveResult); + return LNGResult.of(getSmallestFormula(true, formula, nnf, result.positiveResult)); } private MinimizationResult minimize(final Formula formula, final boolean topLevel) { diff --git a/src/main/java/com/booleworks/logicng/transformations/simplification/QuineMcCluskeySimplifier.java b/src/main/java/com/booleworks/logicng/transformations/simplification/QuineMcCluskeySimplifier.java index dddc5330..818fdd6d 100644 --- a/src/main/java/com/booleworks/logicng/transformations/simplification/QuineMcCluskeySimplifier.java +++ b/src/main/java/com/booleworks/logicng/transformations/simplification/QuineMcCluskeySimplifier.java @@ -7,8 +7,8 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.handlers.ComputationHandler; -import com.booleworks.logicng.handlers.NopHandler; -import com.booleworks.logicng.transformations.AbortableFormulaTransformation; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.transformations.StatelessFormulaTransformation; /** * An implementation of the Quine-McCluskey algorithm for minimizing canonical @@ -19,34 +19,25 @@ * @version 3.0.0 * @since 1.4.0 */ -public class QuineMcCluskeySimplifier extends AbortableFormulaTransformation { +public class QuineMcCluskeySimplifier extends StatelessFormulaTransformation { /** * Constructor. * @param f the formula factory to generate new formulas **/ protected QuineMcCluskeySimplifier(final FormulaFactory f) { - super(f, NopHandler.get()); - } - - /** - * Constructor. - * @param f the formula factory to generate new formulas - * @param handler the optimization handler to abort Quine-McCluskey - **/ - protected QuineMcCluskeySimplifier(final FormulaFactory f, final ComputationHandler handler) { - super(f, handler); + super(f); } @Override - public Formula apply(final Formula formula) { + public LNGResult apply(final Formula formula, ComputationHandler handler) { final var qmcConfig = AdvancedSimplifierConfig.builder() .factorOut(false) .restrictBackbone(false) .simplifyNegations(false) .useRatingFunction(false) .build(); - final var advancedSimplifier = new AdvancedSimplifier(f, qmcConfig, handler); - return formula.transform(advancedSimplifier); + final var advancedSimplifier = new AdvancedSimplifier(f, qmcConfig); + return formula.transform(advancedSimplifier, handler); } } diff --git a/src/test/java/com/booleworks/logicng/LogicNGTest.java b/src/test/java/com/booleworks/logicng/LogicNGTest.java index 13afa720..a44e2269 100644 --- a/src/test/java/com/booleworks/logicng/LogicNGTest.java +++ b/src/test/java/com/booleworks/logicng/LogicNGTest.java @@ -4,16 +4,16 @@ package com.booleworks.logicng; -import com.booleworks.logicng.datastructures.Tristate; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.solvers.SATSolver; -import org.assertj.core.api.Assertions; public interface LogicNGTest { default void assertSolverSat(final SATSolver solver) { - Assertions.assertThat(solver.sat()).isTrue(); + assertThat(solver.sat()).isTrue(); } default void assertSolverUnsat(final SATSolver solver) { - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); } } diff --git a/src/test/java/com/booleworks/logicng/backbones/BackboneGenerationTest.java b/src/test/java/com/booleworks/logicng/backbones/BackboneGenerationTest.java index 9c16983a..9fe06c65 100644 --- a/src/test/java/com/booleworks/logicng/backbones/BackboneGenerationTest.java +++ b/src/test/java/com/booleworks/logicng/backbones/BackboneGenerationTest.java @@ -8,13 +8,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.booleworks.logicng.LongRunningTag; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.BoundedSatHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.DimacsReader; import com.booleworks.logicng.io.readers.FormulaReader; @@ -106,15 +106,14 @@ public void testSimpleBackbones() { SolverState before = solver.saveState(); solver.add(formula); - Assertions.assertThat(solver.execute(BackboneFunction.builder().variables(Collections.emptyList()).build()) + assertThat(solver.execute(BackboneFunction.builder().variables(Collections.emptyList()).build()) .getCompleteBackbone(f)).isEmpty(); solver.loadState(before); formula = x; before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x); solver.loadState(before); @@ -122,8 +121,7 @@ public void testSimpleBackbones() { formula = f.and(x, y); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x, y); solver.loadState(before); @@ -131,8 +129,7 @@ public void testSimpleBackbones() { formula = f.or(x, y); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .isEmpty(); solver.loadState(before); @@ -140,8 +137,7 @@ public void testSimpleBackbones() { formula = x.negate(f); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x.negate(f)); solver.loadState(before); @@ -149,8 +145,7 @@ public void testSimpleBackbones() { formula = f.or(f.and(x, y, z), f.and(x, y, u), f.and(x, u, z)); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x); solver.loadState(before); @@ -158,8 +153,7 @@ public void testSimpleBackbones() { formula = f.and(f.or(x, y, z), f.or(x, y, u), f.or(x, u, z)); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .isEmpty(); solver.loadState(before); @@ -167,8 +161,7 @@ public void testSimpleBackbones() { formula = f.and(f.or(x.negate(f), y), x); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x, y); solver.loadState(before); @@ -176,8 +169,7 @@ public void testSimpleBackbones() { formula = f.and(f.or(x, y), f.or(x.negate(f), y)); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(y); solver.loadState(before); @@ -185,16 +177,14 @@ public void testSimpleBackbones() { formula = f.and(f.and(f.or(x.negate(f), y), x.negate(f)), f.and(z, f.or(x, y))); before = solver.saveState(); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(x.negate(f), y, z); solver.loadState(before); formula = f.and(f.or(x, y), f.or(u, v), z); solver.add(formula); - Assertions - .assertThat( + assertThat( solver.execute(BackboneFunction.builder().variables(variables).build()).getCompleteBackbone(f)) .containsExactly(z); } @@ -227,22 +217,22 @@ private boolean verifyBackbone(final Backbone backbone, final Formula formula, final SATSolver solver = SATSolver.newSolver(formula.factory()); solver.add(formula); for (final Variable bbVar : backbone.getPositiveBackbone()) { - if (solver.satCall().addFormulas(bbVar.negate(f)).sat() == Tristate.TRUE) { + if (solver.satCall().addFormulas(bbVar.negate(f)).sat().getResult()) { return false; } } for (final Variable bbVar : backbone.getNegativeBackbone()) { - if (solver.satCall().addFormulas(bbVar).sat() == Tristate.TRUE) { + if (solver.satCall().addFormulas(bbVar).sat().getResult()) { return false; } } for (final Variable variable : variables) { if (!backbone.getPositiveBackbone().contains(variable) && !backbone.getNegativeBackbone().contains(variable)) { - if (solver.satCall().addFormulas(variable).sat() == Tristate.FALSE) { + if (!solver.satCall().addFormulas(variable).sat().getResult()) { return false; } - if (solver.satCall().addFormulas(variable.negate(f)).sat() == Tristate.FALSE) { + if (!solver.satCall().addFormulas(variable.negate(f)).sat().getResult()) { return false; } } @@ -334,12 +324,9 @@ public void testCancellationPoints() throws IOException { final List formulas = DimacsReader.readCNF(f, "src/test/resources/sat/term1_gr_rcs_w4.shuffled.cnf"); for (int numStarts = 0; numStarts < 10; numStarts++) { final ComputationHandler handler = new BoundedSatHandler(numStarts); - - final Backbone result = BackboneGeneration.compute(f, formulas, FormulaHelper.variables(f, formulas), + final LNGResult result = BackboneGeneration.compute(f, formulas, FormulaHelper.variables(f, formulas), BackboneType.POSITIVE_AND_NEGATIVE, handler); - - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isNull(); + assertThat(result.isSuccess()).isFalse(); } } } diff --git a/src/test/java/com/booleworks/logicng/backbones/BackboneTest.java b/src/test/java/com/booleworks/logicng/backbones/BackboneTest.java index ed9cd03b..5d62261d 100644 --- a/src/test/java/com/booleworks/logicng/backbones/BackboneTest.java +++ b/src/test/java/com/booleworks/logicng/backbones/BackboneTest.java @@ -36,41 +36,41 @@ public class BackboneTest { @Test public void testToFormula() throws ParserException { Backbone backbone = Backbone.satBackbone(set(a1, a2, a3), null, null); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3")); backbone = Backbone.satBackbone(null, set(b1, b2, b3), null); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("~b1 & ~b2 & ~b3")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("~b1 & ~b2 & ~b3")); backbone = Backbone.satBackbone(set(a1, a2, a3), set(b1), null); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3 & ~b1")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3 & ~b1")); backbone = Backbone.satBackbone(set(a1, a2, a3), null, set(x1, x2, x3)); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & a2 & a3")); backbone = Backbone.satBackbone(null, set(b1, b2, b3), set(x1, x2, x3)); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("~b1 & ~b2 & ~b3")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("~b1 & ~b2 & ~b3")); backbone = Backbone.satBackbone(set(a1), set(b1, b2, b3), set(x1)); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & ~b1 & ~b2 & ~b3")); + assertThat(backbone.toFormula(f)).isEqualTo(p.parse("a1 & ~b1 & ~b2 & ~b3")); } @Test public void testToMap() { Backbone backbone = Backbone.satBackbone(set(a1, a2), null, null); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(a1, Tristate.TRUE), MapEntry.entry(a2, Tristate.TRUE) ); backbone = Backbone.satBackbone(null, set(b1, b2, b3), null); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(b1, Tristate.FALSE), MapEntry.entry(b2, Tristate.FALSE), MapEntry.entry(b3, Tristate.FALSE) ); backbone = Backbone.satBackbone(set(a1, a2, a3), set(b1), null); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(a1, Tristate.TRUE), MapEntry.entry(a2, Tristate.TRUE), MapEntry.entry(a3, Tristate.TRUE), MapEntry.entry(b1, Tristate.FALSE) ); backbone = Backbone.satBackbone(set(a1, a2, a3), null, set(x1, x2, x3)); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(a1, Tristate.TRUE), MapEntry.entry(a2, Tristate.TRUE), MapEntry.entry(a3, Tristate.TRUE), @@ -79,7 +79,7 @@ public void testToMap() { MapEntry.entry(x3, Tristate.UNDEF) ); backbone = Backbone.satBackbone(null, set(b1, b2, b3), set(x1, x2, x3)); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(b1, Tristate.FALSE), MapEntry.entry(b2, Tristate.FALSE), MapEntry.entry(b3, Tristate.FALSE), @@ -88,7 +88,7 @@ public void testToMap() { MapEntry.entry(x3, Tristate.UNDEF) ); backbone = Backbone.satBackbone(set(a1), set(b1, b2), set(x1)); - Assertions.assertThat(backbone.toMap()).containsExactly( + assertThat(backbone.toMap()).containsExactly( MapEntry.entry(a1, Tristate.TRUE), MapEntry.entry(b1, Tristate.FALSE), MapEntry.entry(b2, Tristate.FALSE), @@ -99,12 +99,12 @@ public void testToMap() { @Test public void testUnsatBackbone() { final Backbone backbone = Backbone.unsatBackbone(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); - Assertions.assertThat(backbone.getNegativeBackbone()).isEmpty(); - Assertions.assertThat(backbone.getPositiveBackbone()).isEmpty(); - Assertions.assertThat(backbone.getOptionalVariables()).isEmpty(); - Assertions.assertThat(backbone.toMap()).isEmpty(); - Assertions.assertThat(backbone.toFormula(f)).isEqualTo(f.falsum()); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getNegativeBackbone()).isEmpty(); + assertThat(backbone.getPositiveBackbone()).isEmpty(); + assertThat(backbone.getOptionalVariables()).isEmpty(); + assertThat(backbone.toMap()).isEmpty(); + assertThat(backbone.toFormula(f)).isEqualTo(f.falsum()); } @Test diff --git a/src/test/java/com/booleworks/logicng/encodings/CcAlkTest.java b/src/test/java/com/booleworks/logicng/encodings/CcAlkTest.java index 4b384ec7..7e280694 100644 --- a/src/test/java/com/booleworks/logicng/encodings/CcAlkTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/CcAlkTest.java @@ -4,7 +4,6 @@ package com.booleworks.logicng.encodings; -import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -17,7 +16,6 @@ import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.ModelEnumerationFunction; import com.booleworks.logicng.solvers.functions.modelenumeration.ModelEnumerationConfig; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class CcAlkTest implements LogicNGTest { @@ -67,11 +65,10 @@ private void testCC(final FormulaFactory f, final int numLits, final int rhs, fi } final ModelEnumerationFunction me = ModelEnumerationFunction.builder(problemLits) .configuration(ModelEnumerationConfig.builder() - .handler(new NumberOfModelsHandler(12000)) .build()) .build(); - assertThat(solver.execute(me)) + assertThat(solver.execute(me, new NumberOfModelsHandler(12000)).getResult()) .hasSize(expected) .allMatch(m -> m.positiveVariables().size() >= rhs); } diff --git a/src/test/java/com/booleworks/logicng/encodings/CcAmkTest.java b/src/test/java/com/booleworks/logicng/encodings/CcAmkTest.java index 7d8496bc..7f855445 100644 --- a/src/test/java/com/booleworks/logicng/encodings/CcAmkTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/CcAmkTest.java @@ -97,7 +97,7 @@ private void testCC(final FormulaFactory f, final int numLits, final int rhs, fi final SATSolver solver = SATSolver.newSolver(f, SATSolverConfig.builder().useAtMostClauses(miniCard).build()); solver.add(f.cc(CType.LE, rhs, problemLits)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(expected) .allMatch(m -> m.positiveVariables().size() <= rhs); } diff --git a/src/test/java/com/booleworks/logicng/encodings/CcExkTest.java b/src/test/java/com/booleworks/logicng/encodings/CcExkTest.java index 9f2d08d6..df5486eb 100644 --- a/src/test/java/com/booleworks/logicng/encodings/CcExkTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/CcExkTest.java @@ -11,7 +11,6 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.solvers.SATSolver; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class CcExkTest implements LogicNGTest { @@ -57,7 +56,7 @@ private void testCC(final FormulaFactory f, final int numLits, final int rhs, fi } else { assertSolverUnsat(solver); } - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(expected) .allMatch(m -> m.positiveVariables().size() == rhs); } diff --git a/src/test/java/com/booleworks/logicng/encodings/CcExoTest.java b/src/test/java/com/booleworks/logicng/encodings/CcExoTest.java index 83e35925..4226de42 100644 --- a/src/test/java/com/booleworks/logicng/encodings/CcExoTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/CcExoTest.java @@ -54,7 +54,7 @@ public void testEXO1() { final FormulaFactory f = FormulaFactory.caching(); final CardinalityConstraint cc = (CardinalityConstraint) f.exo(f.variable("v0")); for (final EncoderConfig config : configs) { - Assertions.assertThat(CcEncoder.encode(f, cc, config)).containsExactly(f.variable("v0")); + assertThat(CcEncoder.encode(f, cc, config)).containsExactly(f.variable("v0")); } assertThat(f.newCCVariable().name()).endsWith("_0"); } @@ -105,7 +105,7 @@ private void testEXO(final FormulaFactory f, final int numLits) { final SATSolver solver = SATSolver.newSolver(f); solver.add(f.exo(problemLits)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(numLits) .allMatch(m -> m.positiveVariables().size() == 1); } diff --git a/src/test/java/com/booleworks/logicng/encodings/PbEncoderTest.java b/src/test/java/com/booleworks/logicng/encodings/PbEncoderTest.java index 32172c29..23c72caa 100644 --- a/src/test/java/com/booleworks/logicng/encodings/PbEncoderTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/PbEncoderTest.java @@ -4,6 +4,8 @@ package com.booleworks.logicng.encodings; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.LogicNGTest; import com.booleworks.logicng.formulas.CType; import com.booleworks.logicng.formulas.Formula; @@ -13,7 +15,6 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.solvers.SATSolver; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -54,7 +55,7 @@ public void testCC0() { final SATSolver solver = SATSolver.newSolver(f); solver.add(clauses); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(1) .allMatch(m -> m.positiveVariables().isEmpty()); } @@ -79,7 +80,7 @@ public void testCC1() { final SATSolver solver = SATSolver.newSolver(f); solver.add(clauses); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(numLits + 1) .allMatch(m -> m.positiveVariables().size() <= rhs); } @@ -113,7 +114,7 @@ private void testCC(final int numLits, final int rhs, final int expected, final final SATSolver solver = SATSolver.newSolver(f); solver.add(clauses); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(problemLits)) + assertThat(solver.enumerateAllModels(problemLits)) .hasSize(expected) .allMatch(m -> m.positiveVariables().size() <= rhs); } @@ -128,7 +129,7 @@ public void testSpecialCases() { coeffs.add(1); final PBConstraint truePBC = (PBConstraint) f.pbc(CType.GE, 0, lits, coeffs); for (final EncoderConfig config : configs) { - Assertions.assertThat(PbEncoder.encode(f, truePBC, config)).isEmpty(); + assertThat(PbEncoder.encode(f, truePBC, config)).isEmpty(); } } @@ -141,6 +142,6 @@ public void testCCNormalized() throws ParserException { coeffs2.add(2); coeffs2.add(2); final PBConstraint normCC = (PBConstraint) f.pbc(CType.LE, 2, lits, coeffs2); - Assertions.assertThat(PbEncoder.encode(f, normCC, configs.get(0))).containsExactly(f.parse("~m | ~n")); + assertThat(PbEncoder.encode(f, normCC, configs.get(0))).containsExactly(f.parse("~m | ~n")); } } diff --git a/src/test/java/com/booleworks/logicng/encodings/PbSolvingTest.java b/src/test/java/com/booleworks/logicng/encodings/PbSolvingTest.java index ecc25d5c..3cb28d89 100644 --- a/src/test/java/com/booleworks/logicng/encodings/PbSolvingTest.java +++ b/src/test/java/com/booleworks/logicng/encodings/PbSolvingTest.java @@ -16,7 +16,6 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.sat.SolverTestSet; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -176,7 +175,7 @@ public void testCCEQ() { private void testCCAMK(final SATSolver solver, final int rhs, final int expected) { solver.add(f.cc(CType.LE, rhs, literals10)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(expected) .allMatch(model -> model.positiveVariables().size() <= rhs); } @@ -184,7 +183,7 @@ private void testCCAMK(final SATSolver solver, final int rhs, final int expected private void testCCLT(final SATSolver solver, final int rhs, final int expected) { solver.add(f.cc(CType.LT, rhs, literals10)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(expected) .allMatch(model -> model.positiveVariables().size() < rhs); } @@ -192,7 +191,7 @@ private void testCCLT(final SATSolver solver, final int rhs, final int expected) private void testCCALK(final SATSolver solver, final int rhs, final int expected) { solver.add(f.cc(CType.GE, rhs, literals10)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(expected) .allMatch(model -> model.positiveVariables().size() >= rhs); } @@ -200,7 +199,7 @@ private void testCCALK(final SATSolver solver, final int rhs, final int expected private void testCCGT(final SATSolver solver, final int rhs, final int expected) { solver.add(f.cc(CType.GT, rhs, literals10)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(expected) .allMatch(model -> model.positiveVariables().size() > rhs); } @@ -208,7 +207,7 @@ private void testCCGT(final SATSolver solver, final int rhs, final int expected) private void testCCEQ(final SATSolver solver, final int rhs, final int expected) { solver.add(f.cc(CType.EQ, rhs, literals10)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(expected) .allMatch(model -> model.positiveVariables().size() == rhs); } @@ -221,7 +220,7 @@ public void testPBEQ() { final int[] coeffs10 = new int[]{3, 2, 2, 2, 2, 2, 2, 2, 2, 2}; solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.EQ, 5, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(9) .allMatch(model -> model.positiveVariables().size() == 2) .allMatch(model -> model.positiveVariables().contains(f.variable("v" + 0))); @@ -229,14 +228,14 @@ public void testPBEQ() { solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.EQ, 7, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(36) .allMatch(model -> model.positiveVariables().size() == 3) .allMatch(model -> model.positiveVariables().contains(f.variable("v" + 0))); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.EQ, 0, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.EQ, 1, literals10, coeffs10), config)); assertSolverUnsat(solver); @@ -255,31 +254,31 @@ public void testPBLess() { final int[] coeffs10 = new int[]{3, 2, 2, 2, 2, 2, 2, 2, 2, 2}; solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LE, 6, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(140) .allMatch(model -> model.positiveVariables().size() <= 3); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LT, 7, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(140) .allMatch(model -> model.positiveVariables().size() <= 3); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LE, 0, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LE, 1, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LT, 2, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.LT, 1, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); } } } @@ -293,19 +292,19 @@ public void testPBGreater() { solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.GE, 17, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(47) .allMatch(model -> model.positiveVariables().size() >= 8); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.GT, 16, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)) + assertThat(solver.enumerateAllModels(literals10)) .hasSize(47) .allMatch(model -> model.positiveVariables().size() >= 8); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.GE, 21, literals10, coeffs10), config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1); + assertThat(solver.enumerateAllModels(literals10)).hasSize(1); solver = solverSupplier.get(); solver.add(PbEncoder.encode(f, (PBConstraint) f.pbc(CType.GE, 22, literals10, coeffs10), config)); assertSolverUnsat(solver); @@ -325,7 +324,7 @@ public void testPBNegative() { final PBConstraint pbc = (PBConstraint) f.pbc(CType.EQ, 2, literals10, coeffs10); solver.add(PbEncoder.encode(f, pbc, config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(45) + assertThat(solver.enumerateAllModels(literals10)).hasSize(45) .allMatch(m -> pbc.evaluate(m.assignment())); solver = solverSupplier.get(); @@ -333,7 +332,7 @@ public void testPBNegative() { final PBConstraint pbc2 = (PBConstraint) f.pbc(CType.EQ, 4, literals10, coeffs10); solver.add(PbEncoder.encode(f, pbc2, config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(120) + assertThat(solver.enumerateAllModels(literals10)).hasSize(120) .allMatch(m -> pbc2.evaluate(m.assignment())); solver = solverSupplier.get(); @@ -341,7 +340,7 @@ public void testPBNegative() { final PBConstraint pbc3 = (PBConstraint) f.pbc(CType.EQ, 4, literals10, coeffs10); solver.add(PbEncoder.encode(f, pbc3, config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(57) + assertThat(solver.enumerateAllModels(literals10)).hasSize(57) .allMatch(m -> pbc3.evaluate(m.assignment())); solver = solverSupplier.get(); @@ -349,7 +348,7 @@ public void testPBNegative() { final PBConstraint pbc4 = (PBConstraint) f.pbc(CType.EQ, -10, literals10, coeffs10); solver.add(PbEncoder.encode(f, pbc4, config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(8) + assertThat(solver.enumerateAllModels(literals10)).hasSize(8) .allMatch(m -> pbc4.evaluate(m.assignment())); solver = solverSupplier.get(); @@ -357,7 +356,7 @@ public void testPBNegative() { final PBConstraint pbc5 = (PBConstraint) f.pbc(CType.EQ, -12, literals10, coeffs10); solver.add(PbEncoder.encode(f, pbc5, config)); assertSolverSat(solver); - Assertions.assertThat(solver.enumerateAllModels(literals10)).hasSize(1) + assertThat(solver.enumerateAllModels(literals10)).hasSize(1) .allMatch(m -> pbc5.evaluate(m.assignment())); } } diff --git a/src/test/java/com/booleworks/logicng/explanations/UNSATCoreTest.java b/src/test/java/com/booleworks/logicng/explanations/UNSATCoreTest.java index 57ff9237..45ce3719 100644 --- a/src/test/java/com/booleworks/logicng/explanations/UNSATCoreTest.java +++ b/src/test/java/com/booleworks/logicng/explanations/UNSATCoreTest.java @@ -43,8 +43,8 @@ public UNSATCoreTest() throws ParserException { @Test public void testGetters() { - Assertions.assertThat(core1.propositions()).isEqualTo(props1); - Assertions.assertThat(core2.propositions()).isEqualTo(props2); + assertThat(core1.propositions()).isEqualTo(props1); + assertThat(core2.propositions()).isEqualTo(props2); assertThat(core1.isMUS()).isTrue(); assertThat(core2.isMUS()).isFalse(); } @@ -59,10 +59,10 @@ public void testHashCode() { public void testEquals() { assertThat(core1).isEqualTo(core1); assertThat(core1.equals(core1)).isTrue(); - Assertions.assertThat(new UNSATCore<>(props1, true)).isEqualTo(core1); + assertThat(new UNSATCore<>(props1, true)).isEqualTo(core1); assertThat(core2).isNotEqualTo(core1); - Assertions.assertThat(new UNSATCore<>(props1, false)).isNotEqualTo(core1); - Assertions.assertThat(new UNSATCore<>(props2, true)).isNotEqualTo(core1); + assertThat(new UNSATCore<>(props1, false)).isNotEqualTo(core1); + assertThat(new UNSATCore<>(props2, true)).isNotEqualTo(core1); assertThat("String").isNotEqualTo(core1); assertThat(core1).isNotEqualTo("String"); } diff --git a/src/test/java/com/booleworks/logicng/explanations/drup/DRUPTest.java b/src/test/java/com/booleworks/logicng/explanations/drup/DRUPTest.java index 3e6cf159..7cdf001f 100644 --- a/src/test/java/com/booleworks/logicng/explanations/drup/DRUPTest.java +++ b/src/test/java/com/booleworks/logicng/explanations/drup/DRUPTest.java @@ -8,7 +8,6 @@ import com.booleworks.logicng.LogicNGTest; import com.booleworks.logicng.LongRunningTag; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.explanations.UNSATCore; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; @@ -114,7 +113,7 @@ public void testPropositionHandling() throws ParserException { final SATSolver solver = solverSupplier.get(); solver.addPropositions(propositions); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); final UNSATCore unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(propositions.get(0), propositions.get(1), propositions.get(2), propositions.get(3), propositions.get(4), propositions.get(5)); @@ -141,32 +140,32 @@ public void testPropositionIncDec() throws ParserException { final SolverState state2 = solver.saveState(); solver.addPropositions(p7, p8); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); UNSATCore unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state2); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state1); solver.add(p9); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p9); solver.loadState(state1); solver.add(p5); solver.add(p6); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state1); solver.add(p10); solver.add(p11); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); unsatCore = solver.satCall().unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p4, p11); } @@ -231,7 +230,7 @@ public void testCoreAndAssumptions2() throws ParserException { solver.add(f.parse("~A")); solver.sat(); - Assertions.assertThat(solver.satCall().unsatCore()).isNotNull(); + assertThat(solver.satCall().unsatCore()).isNotNull(); } @Test @@ -257,7 +256,7 @@ public void testCoreAndAssumptions3() throws ParserException { solver.add(f.parse("X")); solver.sat(); - Assertions.assertThat(solver.satCall().unsatCore()).isNotNull(); + assertThat(solver.satCall().unsatCore()).isNotNull(); } @Test @@ -273,7 +272,7 @@ public void testCoreAndAssumptions4() throws ParserException { solver.add(f.parse("L & A3 => A4")); solver.add(f.parse("~A4")); solver.add(f.parse("L | R")); - Assertions.assertThat(solver.satCall().unsatCore()).isNotNull(); + assertThat(solver.satCall().unsatCore()).isNotNull(); } @Test @@ -282,7 +281,7 @@ public void testWithAssumptionSolving() throws ParserException { solver.add(f.parse("A1 => A2")); solver.add(f.parse("A2 => ~A1 | ~A3")); try (final SATCall satCall = solver.satCall().addFormulas(f.variable("A3"), f.variable("A1")).solve()) { - assertThat(satCall.getSatResult()).isEqualTo(Tristate.FALSE); + assertThat(satCall.getSatResult().getResult()).isFalse(); } } @@ -300,8 +299,8 @@ public void testWithCcPropositions() throws ParserException { solver.add(p2); solver.add(p3); solver.add(p4); - Assertions.assertThat(solver.sat()).isFalse(); - Assertions.assertThat(solver.satCall().unsatCore().propositions()).containsExactlyInAnyOrder(p1, p2, p3); + assertThat(solver.sat()).isFalse(); + assertThat(solver.satCall().unsatCore().propositions()).containsExactlyInAnyOrder(p1, p2, p3); } @Test @@ -320,10 +319,10 @@ public void testWithSpecialUnitCase() throws ParserException { final StandardProposition p10 = new StandardProposition(f.parse("d => (l + m + e + f = 1)")); final StandardProposition p11 = new StandardProposition(f.parse("~k")); solver.addPropositions(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); - Assertions.assertThat(solver.sat()).isTrue(); + assertThat(solver.sat()).isTrue(); solver.add(f.variable("a")); - Assertions.assertThat(solver.sat()).isFalse(); - Assertions.assertThat(solver.satCall().unsatCore().propositions()).contains(p1, p2, p4, p5, p6, p7, p8, p9, p10, + assertThat(solver.sat()).isFalse(); + assertThat(solver.satCall().unsatCore().propositions()).contains(p1, p2, p4, p5, p6, p7, p8, p9, p10, p11); } diff --git a/src/test/java/com/booleworks/logicng/explanations/mus/MUSConfigTest.java b/src/test/java/com/booleworks/logicng/explanations/mus/MUSConfigTest.java index fc02afc6..7e56c9c6 100644 --- a/src/test/java/com/booleworks/logicng/explanations/mus/MUSConfigTest.java +++ b/src/test/java/com/booleworks/logicng/explanations/mus/MUSConfigTest.java @@ -18,7 +18,7 @@ public class MUSConfigTest { public void testMUSConfiguration() { final MUSConfig config = MUSConfig.builder().algorithm(MUSConfig.Algorithm.valueOf("DELETION")).build(); assertThat(config.toString()).isEqualTo(String.format("MUSConfig{%nalgorithm=DELETION%n}%n")); - Assertions.assertThat(Arrays.asList(CNFConfig.Algorithm.values())) + assertThat(Arrays.asList(CNFConfig.Algorithm.values())) .contains(CNFConfig.Algorithm.valueOf("TSEITIN")); } } diff --git a/src/test/java/com/booleworks/logicng/explanations/mus/MUSGenerationTest.java b/src/test/java/com/booleworks/logicng/explanations/mus/MUSGenerationTest.java index c0c551e0..62834a3a 100644 --- a/src/test/java/com/booleworks/logicng/explanations/mus/MUSGenerationTest.java +++ b/src/test/java/com/booleworks/logicng/explanations/mus/MUSGenerationTest.java @@ -14,11 +14,11 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.handlers.BoundedSatHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.io.readers.DimacsReader; import com.booleworks.logicng.propositions.StandardProposition; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.testutils.PigeonHoleGenerator; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.BufferedReader; @@ -130,14 +130,10 @@ public void testDeletionBasedCancellationPoints() throws IOException { .map(StandardProposition::new) .collect(Collectors.toList()); for (int numStarts = 0; numStarts < 20; numStarts++) { - final ComputationHandler handler = new BoundedSatHandler(numStarts); - final MUSConfig config = - MUSConfig.builder().handler(handler).algorithm(MUSConfig.Algorithm.PLAIN_INSERTION).build(); - - final UNSATCore result = mus.computeMUS(f, propositions, config); - - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isNull(); + final BoundedSatHandler handler = new BoundedSatHandler(numStarts); + final MUSConfig config = MUSConfig.builder().algorithm(MUSConfig.Algorithm.PLAIN_INSERTION).build(); + final LNGResult> result = mus.computeMUS(f, propositions, config, handler); + assertThat(result.isSuccess()).isFalse(); } } @@ -153,12 +149,9 @@ public void testCancellationPoints() throws IOException { for (final MUSConfig.Algorithm algorithm : algorithms) { for (int numStarts = 0; numStarts < 10; numStarts++) { final ComputationHandler handler = new BoundedSatHandler(numStarts); - final MUSConfig config = MUSConfig.builder().handler(handler).algorithm(algorithm).build(); - - final UNSATCore result = mus.computeMUS(f, propositions, config); - - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isNull(); + final MUSConfig config = MUSConfig.builder().algorithm(algorithm).build(); + final LNGResult> result = mus.computeMUS(f, propositions, config, handler); + assertThat(result.isSuccess()).isFalse(); } } } @@ -196,9 +189,9 @@ private void testMUS(final List original, final UNSATCore result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()); + final List result = + SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()).getResult(); assertThat(result).containsExactlyInAnyOrder(f.parse("~s"), f.parse("s|~p"), f.parse("p")); } @@ -57,7 +60,7 @@ public void testWithAdditionalConstraint() throws ParserException { f.parse("~l") ); final List result = - SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))); + SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))).getResult(); assertThat(result).containsExactlyInAnyOrder(f.parse("~n"), f.parse("~l")); } @@ -72,7 +75,7 @@ public void testSatisfiable() throws ParserException { f.parse("~m|l") ); final List result = - SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))); + SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))).getResult(); assertThat(result).isNull(); } @@ -86,7 +89,7 @@ public void testUnsatisfiableAdditionalConstraints() throws ParserException { f.parse("~n|s") ); final List result = - SmusComputation.computeSmusForFormulas(f, input, Arrays.asList(f.parse("~a&b"), f.parse("a|~b"))); + SmusComputation.computeSmusForFormulas(f, input, Arrays.asList(f.parse("~a&b"), f.parse("a|~b"))).getResult(); assertThat(result).isEmpty(); } @@ -104,7 +107,7 @@ public void testTrivialUnsatFormula() throws ParserException { f.parse("a&~a") ); final List result = - SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))); + SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))).getResult(); assertThat(result).containsExactly(f.falsum()); } @@ -122,7 +125,7 @@ public void testUnsatFormula() throws ParserException { f.parse("(a<=>b)&(~a<=>b)") ); final List result = - SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))); + SmusComputation.computeSmusForFormulas(f, input, Collections.singletonList(f.parse("n|l"))).getResult(); assertThat(result).containsExactly(f.parse("(a<=>b)&(~a<=>b)")); } @@ -139,7 +142,7 @@ public void testShorterConflict() throws ParserException { f.parse("~m|l"), f.parse("~l") ); - final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()); + final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()).getResult(); assertThat(result).containsExactlyInAnyOrder(f.parse("s|~p"), f.parse("p&~s")); } @@ -153,7 +156,7 @@ public void testCompleteConflict() throws ParserException { f.parse("n|~l"), f.parse("l|s") ); - final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()); + final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()).getResult(); assertThat(result).containsExactlyInAnyOrderElementsOf(input); } @@ -168,7 +171,7 @@ public void testLongConflictWithShortcut() throws ParserException { f.parse("l|s"), f.parse("n|s") ); - final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()); + final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()).getResult(); assertThat(result).containsExactlyInAnyOrder(f.parse("~s"), f.parse("s|~p"), f.parse("p|~m"), @@ -199,7 +202,7 @@ public void testManyConflicts() throws ParserException { f.parse("x&~y"), f.parse("x=>y") ); - final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()); + final List result = SmusComputation.computeSmusForFormulas(f, input, Collections.emptyList()).getResult(); assertThat(result).containsExactlyInAnyOrder(f.parse("x&~y"), f.parse("x=>y")); } @@ -270,13 +273,8 @@ public void testHSolverCancelled() throws ParserException { private void testHandler(final ComputationHandler handler, final List formulas, final boolean expAborted) { - final List result = + final LNGResult>> result = SmusComputation.computeSmusForFormulas(f, formulas, Collections.emptyList(), handler); - assertThat(handler.isAborted()).isEqualTo(expAborted); - if (expAborted) { - assertThat(result).isNull(); - } else { - assertThat(result).isNotNull(); - } + assertThat(!result.isSuccess()).isEqualTo(expAborted); } } diff --git a/src/test/java/com/booleworks/logicng/formulas/CFalseTest.java b/src/test/java/com/booleworks/logicng/formulas/CFalseTest.java index 2af4a615..728df057 100644 --- a/src/test/java/com/booleworks/logicng/formulas/CFalseTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/CFalseTest.java @@ -58,10 +58,10 @@ public void testEquals(final FormulaContext _c) { @ParameterizedTest @MethodSource("contexts") public void testEqualsDifferentFormulaFactory(final FormulaContext _c) { - Assertions.assertThat(FormulaFactory.caching().falsum()).isEqualTo(_c.falsum); - Assertions.assertThat(FormulaFactory.caching().verum()).isNotEqualTo(_c.falsum); - Assertions.assertThat(FormulaFactory.nonCaching().falsum()).isEqualTo(_c.falsum); - Assertions.assertThat(FormulaFactory.nonCaching().verum()).isNotEqualTo(_c.falsum); + assertThat(FormulaFactory.caching().falsum()).isEqualTo(_c.falsum); + assertThat(FormulaFactory.caching().verum()).isNotEqualTo(_c.falsum); + assertThat(FormulaFactory.nonCaching().falsum()).isEqualTo(_c.falsum); + assertThat(FormulaFactory.nonCaching().verum()).isNotEqualTo(_c.falsum); } @ParameterizedTest diff --git a/src/test/java/com/booleworks/logicng/formulas/CTrueTest.java b/src/test/java/com/booleworks/logicng/formulas/CTrueTest.java index fe2a5825..62568344 100644 --- a/src/test/java/com/booleworks/logicng/formulas/CTrueTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/CTrueTest.java @@ -58,10 +58,10 @@ public void testEquals(final FormulaContext _c) { @ParameterizedTest @MethodSource("contexts") public void testEqualsDifferentFormulaFactory(final FormulaContext _c) { - Assertions.assertThat(FormulaFactory.caching().verum()).isEqualTo(_c.verum); - Assertions.assertThat(FormulaFactory.caching().falsum()).isNotEqualTo(_c.verum); - Assertions.assertThat(FormulaFactory.nonCaching().verum()).isEqualTo(_c.verum); - Assertions.assertThat(FormulaFactory.nonCaching().falsum()).isNotEqualTo(_c.verum); + assertThat(FormulaFactory.caching().verum()).isEqualTo(_c.verum); + assertThat(FormulaFactory.caching().falsum()).isNotEqualTo(_c.verum); + assertThat(FormulaFactory.nonCaching().verum()).isEqualTo(_c.verum); + assertThat(FormulaFactory.nonCaching().falsum()).isNotEqualTo(_c.verum); } @ParameterizedTest diff --git a/src/test/java/com/booleworks/logicng/formulas/CacheTest.java b/src/test/java/com/booleworks/logicng/formulas/CacheTest.java index a8f88bf9..34433c0d 100644 --- a/src/test/java/com/booleworks/logicng/formulas/CacheTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/CacheTest.java @@ -19,19 +19,19 @@ public class CacheTest { @Test public void testDescription() { - Assertions.assertThat(TransformationCacheEntry.AIG.description()) + assertThat(TransformationCacheEntry.AIG.description()) .isEqualTo("TransformationCacheEntry{description=and-inverter graph}"); assertThat(TransformationCacheEntry.NNF.description()) .isEqualTo("TransformationCacheEntry{description=negation normal form}"); assertThat(TransformationCacheEntry.FACTORIZED_CNF.description()) .isEqualTo("TransformationCacheEntry{description=factorized conjunctive normal form}"); - Assertions.assertThat(PredicateCacheEntry.IS_AIG.description()) + assertThat(PredicateCacheEntry.IS_AIG.description()) .isEqualTo("PredicateCacheEntry{description=and-inverter graph}"); assertThat(PredicateCacheEntry.IS_CNF.description()) .isEqualTo("PredicateCacheEntry{description=conjunctive normal form}"); - Assertions.assertThat(FunctionCacheEntry.LITPROFILE.description()) + assertThat(FunctionCacheEntry.LITPROFILE.description()) .isEqualTo("FunctionCacheEntry{description=literal profile}"); assertThat(FunctionCacheEntry.VARPROFILE.description()) .isEqualTo("FunctionCacheEntry{description=variable profile}"); diff --git a/src/test/java/com/booleworks/logicng/formulas/EvaluationTest.java b/src/test/java/com/booleworks/logicng/formulas/EvaluationTest.java index 89ee2880..68ca43be 100644 --- a/src/test/java/com/booleworks/logicng/formulas/EvaluationTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/EvaluationTest.java @@ -66,13 +66,13 @@ public void testNAryEval(final FormulaContext _c) throws ParserException { assertThat(_c.or1.evaluate(ass)).isFalse(); assertThat(_c.or2.evaluate(ass)).isTrue(); assertThat(_c.or3.evaluate(ass)).isTrue(); - Assertions.assertThat(p.parse("~a | ~b | ~c | x | y").evaluate(ass)).isFalse(); - Assertions.assertThat(p.parse("~a | ~b | ~c | x | ~y").evaluate(ass)).isTrue(); + assertThat(p.parse("~a | ~b | ~c | x | y").evaluate(ass)).isFalse(); + assertThat(p.parse("~a | ~b | ~c | x | ~y").evaluate(ass)).isTrue(); assertThat(_c.and1.evaluate(ass)).isTrue(); assertThat(_c.and2.evaluate(ass)).isFalse(); assertThat(_c.and3.evaluate(ass)).isFalse(); - Assertions.assertThat(p.parse("a & b & c & ~x & ~y").evaluate(ass)).isTrue(); - Assertions.assertThat(p.parse("a & b & c & ~x & y").evaluate(ass)).isFalse(); + assertThat(p.parse("a & b & c & ~x & ~y").evaluate(ass)).isTrue(); + assertThat(p.parse("a & b & c & ~x & y").evaluate(ass)).isFalse(); } } diff --git a/src/test/java/com/booleworks/logicng/formulas/FormulaFactoryWithoutContradictionCheckTest.java b/src/test/java/com/booleworks/logicng/formulas/FormulaFactoryWithoutContradictionCheckTest.java index d58ca2d4..c677ff49 100644 --- a/src/test/java/com/booleworks/logicng/formulas/FormulaFactoryWithoutContradictionCheckTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/FormulaFactoryWithoutContradictionCheckTest.java @@ -178,12 +178,12 @@ public void testSatSolverWithTautologies(final FormulaContext _c) throws ParserE solver.add(_c.f.parse("C | ~C")); List models = solver.enumerateAllModels(_c.f.variables("A", "B", "C")); assertThat(models).hasSize(2); - models.forEach(m -> Assertions.assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), + models.forEach(m -> assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), _c.f.literal("C", false))); solver.add(_c.f.parse("D | ~D")); models = solver.enumerateAllModels(_c.f.variables("A", "B", "C", "D")); assertThat(models).hasSize(4); - models.forEach(m -> Assertions.assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), + models.forEach(m -> assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), _c.f.literal("C", false), _c.f.literal("D", true), _c.f.literal("D", false))); } @@ -197,10 +197,10 @@ public void testSatSolverWithContradictions(final FormulaContext _c) throws Pars solver.add(_c.f.parse("C | ~C")); final List models = solver.enumerateAllModels(_c.f.variables("A", "B", "C")); assertThat(models).hasSize(2); - models.forEach(m -> Assertions.assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), + models.forEach(m -> assertThat(m.getLiterals()).containsAnyOf(_c.f.literal("C", true), _c.f.literal("C", false))); solver.add(_c.f.parse("D & ~D")); - Assertions.assertThat(solver.sat()).isFalse(); + assertThat(solver.sat()).isFalse(); } @ParameterizedTest @@ -215,9 +215,9 @@ public void testSubstitution(final FormulaContext _c) throws ParserException { @ParameterizedTest @MethodSource("contexts") public void testBdds(final FormulaContext _c) { - Assertions.assertThat(_c.tautology.bdd(_c.f).isTautology()).isTrue(); - Assertions.assertThat(_c.contradiction.bdd(_c.f).isTautology()).isFalse(); - Assertions.assertThat(_c.tautology.bdd(_c.f).isContradiction()).isFalse(); - Assertions.assertThat(_c.contradiction.bdd(_c.f).isContradiction()).isTrue(); + assertThat(_c.tautology.bdd(_c.f).isTautology()).isTrue(); + assertThat(_c.contradiction.bdd(_c.f).isTautology()).isFalse(); + assertThat(_c.tautology.bdd(_c.f).isContradiction()).isFalse(); + assertThat(_c.contradiction.bdd(_c.f).isContradiction()).isTrue(); } } diff --git a/src/test/java/com/booleworks/logicng/formulas/LiteralTest.java b/src/test/java/com/booleworks/logicng/formulas/LiteralTest.java index cbcd4918..59f8c96c 100644 --- a/src/test/java/com/booleworks/logicng/formulas/LiteralTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/LiteralTest.java @@ -7,7 +7,6 @@ import static org.assertj.core.api.Assertions.assertThat; import com.booleworks.logicng.datastructures.Substitution; -import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -95,17 +94,17 @@ public void testEquals(final FormulaContext _c) { @ParameterizedTest @MethodSource("contexts") public void testEqualsDifferentFormulaFactory(final FormulaContext _c) { - Assertions.assertThat(FormulaFactory.caching().literal("a", true).equals(_c.a)).isTrue(); - Assertions.assertThat(FormulaFactory.caching().literal("a", false).equals(_c.na)).isTrue(); - Assertions.assertThat(FormulaFactory.caching().literal("a", false).equals(_c.a)).isFalse(); - Assertions.assertThat(FormulaFactory.caching().literal("b", true).equals(_c.a)).isFalse(); - Assertions.assertThat(FormulaFactory.caching().falsum()).isNotEqualTo(_c.a); - - Assertions.assertThat(FormulaFactory.nonCaching().literal("a", true).equals(_c.a)).isTrue(); - Assertions.assertThat(FormulaFactory.nonCaching().literal("a", false).equals(_c.na)).isTrue(); - Assertions.assertThat(FormulaFactory.nonCaching().literal("a", false).equals(_c.a)).isFalse(); - Assertions.assertThat(FormulaFactory.nonCaching().literal("b", true).equals(_c.a)).isFalse(); - Assertions.assertThat(FormulaFactory.nonCaching().falsum()).isNotEqualTo(_c.a); + assertThat(FormulaFactory.caching().literal("a", true).equals(_c.a)).isTrue(); + assertThat(FormulaFactory.caching().literal("a", false).equals(_c.na)).isTrue(); + assertThat(FormulaFactory.caching().literal("a", false).equals(_c.a)).isFalse(); + assertThat(FormulaFactory.caching().literal("b", true).equals(_c.a)).isFalse(); + assertThat(FormulaFactory.caching().falsum()).isNotEqualTo(_c.a); + + assertThat(FormulaFactory.nonCaching().literal("a", true).equals(_c.a)).isTrue(); + assertThat(FormulaFactory.nonCaching().literal("a", false).equals(_c.na)).isTrue(); + assertThat(FormulaFactory.nonCaching().literal("a", false).equals(_c.a)).isFalse(); + assertThat(FormulaFactory.nonCaching().literal("b", true).equals(_c.a)).isFalse(); + assertThat(FormulaFactory.nonCaching().falsum()).isNotEqualTo(_c.a); } @ParameterizedTest diff --git a/src/test/java/com/booleworks/logicng/formulas/NNFTest.java b/src/test/java/com/booleworks/logicng/formulas/NNFTest.java index 9020dbf8..61fc16bb 100644 --- a/src/test/java/com/booleworks/logicng/formulas/NNFTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/NNFTest.java @@ -44,26 +44,26 @@ public void testBinaryOperators(final FormulaContext _c) throws ParserException public void testNAryOperators(final FormulaContext _c) throws ParserException { assertThat(_c.and1.nnf(_c.f)).isEqualTo(_c.and1); assertThat(_c.or1.nnf(_c.f)).isEqualTo(_c.or1); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").nnf(_c.f)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").nnf(_c.f)) .isEqualTo(_c.p.parse("~a & ~b & c & (~x | y) & (~w | z)")); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y) | (w => z)").nnf(_c.f)) + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y) | (w => z)").nnf(_c.f)) .isEqualTo(_c.p.parse("~a | ~b | c | (~x & y) | (~w | z)")); } @ParameterizedTest @MethodSource("contexts") public void testNot(final FormulaContext _c) throws ParserException { - Assertions.assertThat(_c.p.parse("~a").nnf(_c.f)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").nnf(_c.f)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").nnf(_c.f)).isEqualTo(_c.p.parse("a & ~b")); - Assertions.assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").nnf(_c.f)) + assertThat(_c.p.parse("~a").nnf(_c.f)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").nnf(_c.f)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").nnf(_c.f)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").nnf(_c.f)) .isEqualTo(_c.p.parse("~a & ~b & (x | y)")); - Assertions.assertThat(_c.p.parse("a <=> b").nnf(_c.f)).isEqualTo(_c.p.parse("(~a | b) & (~b | a)")); - Assertions.assertThat(_c.p.parse("~(a <=> b)").nnf(_c.f)).isEqualTo(_c.p.parse("(~a | ~b) & (a | b)")); - Assertions.assertThat(_c.p.parse("~(~(a | b) <=> ~(x | y))").nnf(_c.f)) + assertThat(_c.p.parse("a <=> b").nnf(_c.f)).isEqualTo(_c.p.parse("(~a | b) & (~b | a)")); + assertThat(_c.p.parse("~(a <=> b)").nnf(_c.f)).isEqualTo(_c.p.parse("(~a | ~b) & (a | b)")); + assertThat(_c.p.parse("~(~(a | b) <=> ~(x | y))").nnf(_c.f)) .isEqualTo(_c.p.parse("((a | b) | (x | y)) & ((~a & ~b) | (~x & ~y))")); - Assertions.assertThat(_c.p.parse("~(a & b & ~x & ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a | ~b | x | y")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a & ~b & x & y")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a & ~b & x & y")); + assertThat(_c.p.parse("~(a & b & ~x & ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a | ~b | x | y")); + assertThat(_c.p.parse("~(a | b | ~x | ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a & ~b & x & y")); + assertThat(_c.p.parse("~(a | b | ~x | ~y)").nnf(_c.f)).isEqualTo(_c.p.parse("~a & ~b & x & y")); } } diff --git a/src/test/java/com/booleworks/logicng/formulas/PBConstraintTest.java b/src/test/java/com/booleworks/logicng/formulas/PBConstraintTest.java index 84071d49..bc8609fd 100644 --- a/src/test/java/com/booleworks/logicng/formulas/PBConstraintTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/PBConstraintTest.java @@ -658,35 +658,35 @@ public void testAtomicFormula(final FormulaContext _c) { @Test public void testEvaluateCoeffs() { - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.EQ)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.EQ)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.EQ)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.EQ)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.EQ)).isEqualTo(Tristate.UNDEF); - - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.GE)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.GE)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.GE)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.GE)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.GE)).isEqualTo(Tristate.UNDEF); - - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.GT)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.GT)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.GT)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.GT)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.GT)).isEqualTo(Tristate.UNDEF); - - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.LE)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.LE)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.LE)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.LE)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.LE)).isEqualTo(Tristate.UNDEF); - - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.LT)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.LT)).isEqualTo(Tristate.TRUE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.LT)).isEqualTo(Tristate.FALSE); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.LT)).isEqualTo(Tristate.UNDEF); - Assertions.assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.LT)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.EQ)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.EQ)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.EQ)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.EQ)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.EQ)).isEqualTo(Tristate.UNDEF); + + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.GE)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.GE)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.GE)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.GE)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.GE)).isEqualTo(Tristate.UNDEF); + + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.GT)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.GT)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.GT)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.GT)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.GT)).isEqualTo(Tristate.UNDEF); + + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.LE)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.LE)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.LE)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.LE)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.LE)).isEqualTo(Tristate.UNDEF); + + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -3, CType.LT)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 3, CType.LT)).isEqualTo(Tristate.TRUE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, -2, CType.LT)).isEqualTo(Tristate.FALSE); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 2, CType.LT)).isEqualTo(Tristate.UNDEF); + assertThat(PBConstraint.evaluateCoeffs(-2, 2, 0, CType.LT)).isEqualTo(Tristate.UNDEF); } @ParameterizedTest diff --git a/src/test/java/com/booleworks/logicng/formulas/RestrictionTest.java b/src/test/java/com/booleworks/logicng/formulas/RestrictionTest.java index 36abb58f..64fd47db 100644 --- a/src/test/java/com/booleworks/logicng/formulas/RestrictionTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/RestrictionTest.java @@ -67,13 +67,13 @@ public void testNAryRestrict(final FormulaContext _c) throws ParserException { assertThat(_c.or1.restrict(_c.f, ass)).isEqualTo(_c.y); assertThat(_c.or2.restrict(_c.f, ass)).isEqualTo(_c.verum); assertThat(_c.or3.restrict(_c.f, ass)).isEqualTo(_c.falsum); - Assertions.assertThat(_c.p.parse("~a | b | ~c | x | y").restrict(_c.f, ass)).isEqualTo(_c.p.parse("~c | y")); - Assertions.assertThat(_c.p.parse("~a | b | ~c | ~x | ~y").restrict(_c.f, ass)).isEqualTo(_c.verum); + assertThat(_c.p.parse("~a | b | ~c | x | y").restrict(_c.f, ass)).isEqualTo(_c.p.parse("~c | y")); + assertThat(_c.p.parse("~a | b | ~c | ~x | ~y").restrict(_c.f, ass)).isEqualTo(_c.verum); assertThat(_c.and1.restrict(_c.f, ass)).isEqualTo(_c.falsum); assertThat(_c.and2.restrict(_c.f, ass)).isEqualTo(_c.falsum); assertThat(_c.and3.restrict(_c.f, ass)).isEqualTo(_c.y); - Assertions.assertThat(_c.p.parse("a & ~b & c & ~x & ~y").restrict(_c.f, ass)).isEqualTo(_c.p.parse("c & ~y")); - Assertions.assertThat(_c.p.parse("a & b & c & ~x & y").restrict(_c.f, ass)).isEqualTo(_c.falsum); + assertThat(_c.p.parse("a & ~b & c & ~x & ~y").restrict(_c.f, ass)).isEqualTo(_c.p.parse("c & ~y")); + assertThat(_c.p.parse("a & b & c & ~x & y").restrict(_c.f, ass)).isEqualTo(_c.falsum); } } diff --git a/src/test/java/com/booleworks/logicng/formulas/SubstitutionTest.java b/src/test/java/com/booleworks/logicng/formulas/SubstitutionTest.java index b2a73090..8cd8b995 100644 --- a/src/test/java/com/booleworks/logicng/formulas/SubstitutionTest.java +++ b/src/test/java/com/booleworks/logicng/formulas/SubstitutionTest.java @@ -132,7 +132,7 @@ public void testEquals() { subst3.addMapping(_s.c, _s.and1); assertThat(subst2).isEqualTo(subst); assertThat(subst).isEqualTo(subst); - Assertions.assertThat(new Assignment()).isNotEqualTo(subst); + assertThat(new Assignment()).isNotEqualTo(subst); assertThat(subst3).isNotEqualTo(subst); } diff --git a/src/test/java/com/booleworks/logicng/functions/FormulaDepthFunctionTest.java b/src/test/java/com/booleworks/logicng/functions/FormulaDepthFunctionTest.java index 5f64533d..012814bf 100644 --- a/src/test/java/com/booleworks/logicng/functions/FormulaDepthFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/functions/FormulaDepthFunctionTest.java @@ -30,15 +30,15 @@ public class FormulaDepthFunctionTest extends TestWithFormulaContext { public void testAtoms(final FormulaContext _c) { final FormulaDepthFunction df = new FormulaDepthFunction(_c.f); - Assertions.assertThat(_c.verum.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.falsum.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.a.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.na.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.pbc1.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.pbc2.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.pbc3.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.pbc4.apply(df)).isEqualTo(0); - Assertions.assertThat(_c.pbc5.apply(df)).isEqualTo(0); + assertThat(_c.verum.apply(df)).isEqualTo(0); + assertThat(_c.falsum.apply(df)).isEqualTo(0); + assertThat(_c.a.apply(df)).isEqualTo(0); + assertThat(_c.na.apply(df)).isEqualTo(0); + assertThat(_c.pbc1.apply(df)).isEqualTo(0); + assertThat(_c.pbc2.apply(df)).isEqualTo(0); + assertThat(_c.pbc3.apply(df)).isEqualTo(0); + assertThat(_c.pbc4.apply(df)).isEqualTo(0); + assertThat(_c.pbc5.apply(df)).isEqualTo(0); } @ParameterizedTest @@ -46,22 +46,22 @@ public void testAtoms(final FormulaContext _c) { public void testDeepFormulas(final FormulaContext _c) { final FormulaDepthFunction df = new FormulaDepthFunction(_c.f); - Assertions.assertThat(_c.and1.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.and2.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.and3.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.or1.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.or2.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.or3.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.not1.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.not2.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.imp1.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.imp2.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.imp3.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.imp4.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.eq1.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.eq2.apply(df)).isEqualTo(1); - Assertions.assertThat(_c.eq3.apply(df)).isEqualTo(2); - Assertions.assertThat(_c.eq4.apply(df)).isEqualTo(2); + assertThat(_c.and1.apply(df)).isEqualTo(1); + assertThat(_c.and2.apply(df)).isEqualTo(1); + assertThat(_c.and3.apply(df)).isEqualTo(2); + assertThat(_c.or1.apply(df)).isEqualTo(1); + assertThat(_c.or2.apply(df)).isEqualTo(1); + assertThat(_c.or3.apply(df)).isEqualTo(2); + assertThat(_c.not1.apply(df)).isEqualTo(2); + assertThat(_c.not2.apply(df)).isEqualTo(2); + assertThat(_c.imp1.apply(df)).isEqualTo(1); + assertThat(_c.imp2.apply(df)).isEqualTo(1); + assertThat(_c.imp3.apply(df)).isEqualTo(2); + assertThat(_c.imp4.apply(df)).isEqualTo(2); + assertThat(_c.eq1.apply(df)).isEqualTo(1); + assertThat(_c.eq2.apply(df)).isEqualTo(1); + assertThat(_c.eq3.apply(df)).isEqualTo(2); + assertThat(_c.eq4.apply(df)).isEqualTo(2); } @ParameterizedTest @@ -74,7 +74,7 @@ public void testDeeperFormulas(final FormulaContext _c) { final Variable var = _c.f.variable("X" + i); formula = i % 2 == 0 ? _c.f.or(formula, var) : _c.f.and(formula, var); } - Assertions.assertThat(formula.apply(df)).isEqualTo(10); + assertThat(formula.apply(df)).isEqualTo(10); } @Test @@ -85,11 +85,11 @@ public void testCacheCachingFF() throws ParserException { final Formula formula = f.parse("A & B | C"); final Map cache = f.getFunctionCacheForType(FunctionCacheEntry.DEPTH); assertThat(cache.get(formula)).isNull(); - Assertions.assertThat(formula.apply(df)).isEqualTo(2); + assertThat(formula.apply(df)).isEqualTo(2); assertThat(cache.get(formula)).isEqualTo(2); assertThat(cache.get(f.variable("A"))).isEqualTo(0); cache.put(formula, 3); - Assertions.assertThat(formula.apply(df)).isEqualTo(3); + assertThat(formula.apply(df)).isEqualTo(3); } @Test @@ -102,16 +102,16 @@ public void testCacheCachingOwnCache() throws ParserException { final Map ffCache = f.getFunctionCacheForType(FunctionCacheEntry.DEPTH); assertThat(cache.get(formula)).isNull(); - Assertions.assertThat(formula.apply(df)).isEqualTo(2); + assertThat(formula.apply(df)).isEqualTo(2); assertThat(cache.get(formula)).isEqualTo(2); assertThat(cache.get(f.variable("A"))).isEqualTo(0); cache.put(formula, 3); - Assertions.assertThat(formula.apply(df)).isEqualTo(3); + assertThat(formula.apply(df)).isEqualTo(3); assertThat(ffCache.get(formula)).isNull(); assertThat(ffCache.get(f.variable("A"))).isNull(); ffCache.put(formula, 5); - Assertions.assertThat(formula.apply(df)).isEqualTo(3); + assertThat(formula.apply(df)).isEqualTo(3); } @Test @@ -122,10 +122,10 @@ public void testCacheNonCaching() throws ParserException { final Formula formula = f.parse("A & B | C"); assertThat(cache.get(formula)).isNull(); - Assertions.assertThat(formula.apply(df)).isEqualTo(2); + assertThat(formula.apply(df)).isEqualTo(2); assertThat(cache.get(formula)).isEqualTo(2); assertThat(cache.get(f.variable("A"))).isEqualTo(0); cache.put(formula, 3); - Assertions.assertThat(formula.apply(df)).isEqualTo(3); + assertThat(formula.apply(df)).isEqualTo(3); } } diff --git a/src/test/java/com/booleworks/logicng/functions/MinimumPrimeImplicantTest.java b/src/test/java/com/booleworks/logicng/functions/MinimumPrimeImplicantTest.java index 3f3fc7c6..29f257d7 100644 --- a/src/test/java/com/booleworks/logicng/functions/MinimumPrimeImplicantTest.java +++ b/src/test/java/com/booleworks/logicng/functions/MinimumPrimeImplicantTest.java @@ -30,46 +30,46 @@ public MinimumPrimeImplicantTest() { @Test public void testSimpleCases() throws ParserException { Formula formula = f.parse("a"); - SortedSet pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + SortedSet pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(1); isPrimeImplicant(formula, pi); formula = f.parse("a | b | c"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(1); isPrimeImplicant(formula, pi); formula = f.parse("a & b & (~a|~b)"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).isNull(); formula = f.parse("a & b & c"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(3); isPrimeImplicant(formula, pi); formula = f.parse("a | b | ~c => e & d & f"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(3); isPrimeImplicant(formula, pi); formula = f.parse("a | b | ~c <=> e & d & f"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(4); isPrimeImplicant(formula, pi); formula = f.parse("(a | b | ~c <=> e & d & f) | (a | b | ~c => e & d & f)"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(3); isPrimeImplicant(formula, pi); formula = f.parse("(a | b | ~c <=> e & d & f) | (a | b | ~c => e & d & f) | (a & b)"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(2); isPrimeImplicant(formula, pi); formula = f.parse("(a | b | ~c <=> e & d & f) | (a | b | ~c => e & d & f) | (a & b) | (f => g)"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(1); isPrimeImplicant(formula, pi); } @@ -77,18 +77,18 @@ public void testSimpleCases() throws ParserException { @Test public void testSmallExamples() throws ParserException { Formula formula = f.parse("(~(v17 | v18) | ~v1494 & (v17 | v18)) & ~v687 => v686"); - SortedSet pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + SortedSet pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(1); isPrimeImplicant(formula, pi); formula = f.parse("(~(v17 | v18) | ~v1494 & (v17 | v18)) & v687 => ~v686"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(1); isPrimeImplicant(formula, pi); formula = f.parse( "v173 + v174 + v451 + v258 + v317 + v259 + v452 + v453 + v175 + v176 + v177 + v178 + v179 + v180 + v181 + v182 + v183 + v102 + v103 + v104 + v105 = 1"); - pi = formula.apply(new MinimumPrimeImplicantFunction(f)); + pi = formula.apply(new MinimumPrimeImplicantFunction(f)).getResult(); assertThat(pi).hasSize(21); isPrimeImplicant(formula, pi); } @@ -97,7 +97,7 @@ public void testSmallExamples() throws ParserException { public void testMiddleExamples() throws IOException, ParserException { final Formula parsed = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/formula1.txt"); for (final Formula formula : parsed) { - isPrimeImplicant(formula, formula.apply(new MinimumPrimeImplicantFunction(f))); + isPrimeImplicant(formula, formula.apply(new MinimumPrimeImplicantFunction(f)).getResult()); } } @@ -106,7 +106,7 @@ public void testLargeExamples() throws IOException, ParserException { final Formula parsed = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/small_formulas.txt"); for (final Formula formula : parsed) { - isPrimeImplicant(formula, formula.apply(new MinimumPrimeImplicantFunction(f))); + isPrimeImplicant(formula, formula.apply(new MinimumPrimeImplicantFunction(f)).getResult()); } } diff --git a/src/test/java/com/booleworks/logicng/functions/SubformulaTest.java b/src/test/java/com/booleworks/logicng/functions/SubformulaTest.java index 868e5fe4..7a2bf98a 100644 --- a/src/test/java/com/booleworks/logicng/functions/SubformulaTest.java +++ b/src/test/java/com/booleworks/logicng/functions/SubformulaTest.java @@ -175,7 +175,7 @@ public void subformulasTest(final FormulaContext _c) throws ParserException { expected.add(_c.p.parse("(~x | y) & (x | ~z)")); expected.add(_c.p.parse("a => (~x | y) & (x | ~z)")); expected.add(_c.p.parse("((a & ~b & c) | (d & (~e | c))) & (a => (~x | y) & (x | ~z))")); - Assertions.assertThat(f1.apply(new SubNodeFunction(_c.f))).isEqualTo(expected); + assertThat(f1.apply(new SubNodeFunction(_c.f))).isEqualTo(expected); } @Test diff --git a/src/test/java/com/booleworks/logicng/graphs/generators/ConstraintGraphGeneratorTest.java b/src/test/java/com/booleworks/logicng/graphs/generators/ConstraintGraphGeneratorTest.java index bd195250..2354dabd 100644 --- a/src/test/java/com/booleworks/logicng/graphs/generators/ConstraintGraphGeneratorTest.java +++ b/src/test/java/com/booleworks/logicng/graphs/generators/ConstraintGraphGeneratorTest.java @@ -18,7 +18,6 @@ import com.booleworks.logicng.io.parsers.PropositionalParser; import com.booleworks.logicng.io.readers.FormulaReader; import com.booleworks.logicng.transformations.cnf.CNFFactorization; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -32,8 +31,8 @@ public class ConstraintGraphGeneratorTest { public void testSimple() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(ConstraintGraphGenerator.generateFromFormulas(f, List.of(f.falsum())).nodes()).isEmpty(); - Assertions.assertThat(ConstraintGraphGenerator.generateFromFormulas(f, f.verum()).nodes()).isEmpty(); + assertThat(ConstraintGraphGenerator.generateFromFormulas(f, List.of(f.falsum())).nodes()).isEmpty(); + assertThat(ConstraintGraphGenerator.generateFromFormulas(f, f.verum()).nodes()).isEmpty(); Graph graph = ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a")); assertThat(graph.nodes()).containsExactly(graph.node(f.variable("a"))); graph = ConstraintGraphGenerator.generateFromFormulas(f, p.parse("~a")); @@ -51,7 +50,7 @@ public void testOr() throws ParserException { expected.connect(a, b); expected.connect(a, c); expected.connect(b, c); - Assertions.assertThat(ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a | ~b | c")).toString()) + assertThat(ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a | ~b | c")).toString()) .isEqualTo(expected.toString()); } @@ -66,7 +65,7 @@ public void testCC() throws ParserException { expected.connect(a, b); expected.connect(a, c); expected.connect(b, c); - Assertions.assertThat(ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a + b + c <= 1")).toString()) + assertThat(ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a + b + c <= 1")).toString()) .isEqualTo(expected.toString()); } @@ -86,7 +85,7 @@ public void testCnf() throws ParserException { expected.connect(b, c); expected.connect(d, a); expected.connect(d, e); - Assertions.assertThat(ConstraintGraphGenerator.generateFromFormulas(f, + assertThat(ConstraintGraphGenerator.generateFromFormulas(f, p.parse("a | ~b | c"), p.parse("d | ~a"), p.parse("d + e = 1"), diff --git a/src/test/java/com/booleworks/logicng/graphs/generators/HypergraphGeneratorTest.java b/src/test/java/com/booleworks/logicng/graphs/generators/HypergraphGeneratorTest.java index ae9e4e03..f740883b 100644 --- a/src/test/java/com/booleworks/logicng/graphs/generators/HypergraphGeneratorTest.java +++ b/src/test/java/com/booleworks/logicng/graphs/generators/HypergraphGeneratorTest.java @@ -25,10 +25,10 @@ public class HypergraphGeneratorTest { public void testCNF() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, p.parse("$false")).nodes()).isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, p.parse("$false")).edges()).isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, p.parse("$true")).nodes()).isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, p.parse("$true")).edges()).isEmpty(); + assertThat(HypergraphGenerator.fromCNF(f, p.parse("$false")).nodes()).isEmpty(); + assertThat(HypergraphGenerator.fromCNF(f, p.parse("$false")).edges()).isEmpty(); + assertThat(HypergraphGenerator.fromCNF(f, p.parse("$true")).nodes()).isEmpty(); + assertThat(HypergraphGenerator.fromCNF(f, p.parse("$true")).edges()).isEmpty(); Hypergraph hypergraph = HypergraphGenerator.fromCNF(f, p.parse("A")); HypergraphNode nodeA = new HypergraphNode<>(hypergraph, f.variable("A")); @@ -67,13 +67,13 @@ public void testCNF() throws ParserException { public void testCNFFromList() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$false"))).nodes()) + assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$false"))).nodes()) .isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$false"))).edges()) + assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$false"))).edges()) .isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$true"))).nodes()) + assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$true"))).nodes()) .isEmpty(); - Assertions.assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$true"))).edges()) + assertThat(HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("$true"))).edges()) .isEmpty(); Hypergraph hypergraph = HypergraphGenerator.fromCNF(f, Collections.singletonList(p.parse("A"))); diff --git a/src/test/java/com/booleworks/logicng/handlers/BoundedOptimizationHandler.java b/src/test/java/com/booleworks/logicng/handlers/BoundedOptimizationHandler.java index 116c3795..4c99a18d 100644 --- a/src/test/java/com/booleworks/logicng/handlers/BoundedOptimizationHandler.java +++ b/src/test/java/com/booleworks/logicng/handlers/BoundedOptimizationHandler.java @@ -5,7 +5,7 @@ package com.booleworks.logicng.handlers; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * Bounded optimization handler for testing purposes. @@ -36,12 +36,7 @@ public BoundedOptimizationHandler(final int satStartsLimit, final int startsLimi } @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event instanceof ComputationStartedEvent) { if (event == ComputationStartedEvent.SAT_CALL_STARTED) { aborted |= satStartsLimit != -1 && ++numSatStarts >= satStartsLimit; diff --git a/src/test/java/com/booleworks/logicng/handlers/BoundedSatHandler.java b/src/test/java/com/booleworks/logicng/handlers/BoundedSatHandler.java index 1f312778..99e37b38 100644 --- a/src/test/java/com/booleworks/logicng/handlers/BoundedSatHandler.java +++ b/src/test/java/com/booleworks/logicng/handlers/BoundedSatHandler.java @@ -5,7 +5,7 @@ package com.booleworks.logicng.handlers; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; /** * Bounded SAT handler for testing purposes. @@ -28,13 +28,12 @@ public BoundedSatHandler(final int startsLimit) { numStarts = 0; } - @Override public boolean isAborted() { return aborted; } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == ComputationStartedEvent.SAT_CALL_STARTED) { aborted = startsLimit != -1 && ++numStarts >= startsLimit; } diff --git a/src/test/java/com/booleworks/logicng/handlers/ModelEnumerationHandlerTest.java b/src/test/java/com/booleworks/logicng/handlers/ModelEnumerationHandlerTest.java index 1f3596e8..2a3e715e 100644 --- a/src/test/java/com/booleworks/logicng/handlers/ModelEnumerationHandlerTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/ModelEnumerationHandlerTest.java @@ -10,6 +10,7 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.events.SimpleEvent; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.solvers.SATSolver; import com.booleworks.logicng.solvers.functions.ModelCountingFunction; @@ -39,21 +40,19 @@ public void testTimeoutHandler() throws ParserException, InterruptedException { solver.add(formula); final TimeoutHandler handler = new TimeoutHandler(100); final ModelCountingFunction enumeration = ModelCountingFunction.builder(formula.variables(f)) - .configuration(ModelEnumerationConfig.builder().handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().build()) .build(); - Thread.sleep(150); - assertThat(handler.isAborted()).isFalse(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isTrue(); final long start = System.currentTimeMillis(); - solver.execute(enumeration); + final LNGResult result = solver.execute(enumeration, handler); final long finish = System.currentTimeMillis(); final long timeElapsed = finish - start; // Should be very unlikely that the formula can be fully enumerated in - // 100ms. - // Thus, we expect the handler to stop the execution. - assertThat(handler.isAborted()).isTrue(); + // 100ms. Thus, we expect the handler to stop the execution. + assertThat(result.isSuccess()).isFalse(); assertThat(timeElapsed).isGreaterThanOrEqualTo(100L); } @@ -67,13 +66,15 @@ public void testNumberOfModelsHandler() throws ParserException { solver.add(formula); final NumberOfModelsHandler handler = new NumberOfModelsHandler(i); final ModelCountingFunction enumeration = ModelCountingFunction.builder(vars) - .configuration(ModelEnumerationConfig.builder().handler(handler).strategy( - DefaultModelEnumerationStrategy.builder().maxNumberOfModels(200).build() - ).build() + .configuration(ModelEnumerationConfig.builder() + .strategy(DefaultModelEnumerationStrategy.builder().maxNumberOfModels(200).build()) + .build() ).build(); - final BigInteger numberOfModels = solver.execute(enumeration); - assertThat(handler.isAborted()).isTrue(); - assertThat(numberOfModels.longValueExact()).isLessThanOrEqualTo(i); + final LNGResult numberOfModels = solver.execute(enumeration, handler); + assertThat(numberOfModels.isSuccess()).isFalse(); + assertThat(numberOfModels).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial) numberOfModels).getPartialResult() + .get().longValueExact()).isLessThanOrEqualTo(i + 8); // because of 3 dont cares } } } diff --git a/src/test/java/com/booleworks/logicng/handlers/TimeoutBDDHandlerTest.java b/src/test/java/com/booleworks/logicng/handlers/TimeoutBDDHandlerTest.java index acbd3319..7aa34081 100644 --- a/src/test/java/com/booleworks/logicng/handlers/TimeoutBDDHandlerTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/TimeoutBDDHandlerTest.java @@ -7,6 +7,7 @@ import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.BDD_COMPUTATION_STARTED; import static com.booleworks.logicng.handlers.events.SimpleEvent.BDD_NEW_REF_ADDED; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.times; @@ -57,9 +58,9 @@ public void testThatMethodsAreCalled() throws ParserException { final VariableOrderingProvider provider = new BFSOrdering(); final BDDKernel kernel = new BDDKernel(f, provider.getOrder(f, formula), 100, 100); final TimeoutHandler handler = Mockito.mock(TimeoutHandler.class); + when(handler.shouldResume(any())).thenReturn(true); BDDFactory.build(f, formula, kernel, handler); - verify(handler, times(1)).shouldResume(eq(BDD_COMPUTATION_STARTED)); verify(handler, atLeast(1)).shouldResume(eq(BDD_NEW_REF_ADDED)); } @@ -74,10 +75,8 @@ public void testThatNewRefAddedHandledProperly() throws ParserException { when(handler.shouldResume(eq(BDD_COMPUTATION_STARTED))).thenReturn(true); when(handler.shouldResume(eq(BDD_NEW_REF_ADDED))).thenAnswer(invocationOnMock -> count.addAndGet(1) < 5); - final BDD result = BDDFactory.build(f, formula, kernel, handler); - - assertThat(result).isEqualTo(new BDD(BDDKernel.BDD_ABORT, kernel)); - + final LNGResult result = BDDFactory.build(f, formula, kernel, handler); + assertThat(result.isSuccess()).isFalse(); verify(handler, times(1)).shouldResume(eq(BDD_COMPUTATION_STARTED)); verify(handler, times(5)).shouldResume(eq(BDD_NEW_REF_ADDED)); } @@ -89,10 +88,8 @@ public void testTimeoutHandlerSingleTimeout() { final BDDKernel kernel = new BDDKernel(f, provider.getOrder(f, formula), 100, 100); final TimeoutHandler handler = new TimeoutHandler(100L); - final BDD result = BDDFactory.build(f, formula, kernel, handler); - - assertThat(handler.aborted).isTrue(); - assertThat(result).isEqualTo(new BDD(BDDKernel.BDD_ABORT, kernel)); + final LNGResult result = BDDFactory.build(f, formula, kernel, handler); + assertThat(result.isSuccess()).isFalse(); } @Test @@ -103,9 +100,7 @@ public void testTimeoutHandlerFixedEnd() { final TimeoutHandler handler = new TimeoutHandler(System.currentTimeMillis() + 100L, TimeoutHandler.TimerType.FIXED_END); - final BDD result = BDDFactory.build(f, formula, kernel, handler); - - assertThat(handler.aborted).isTrue(); - assertThat(result).isEqualTo(new BDD(BDDKernel.BDD_ABORT, kernel)); + final LNGResult result = BDDFactory.build(f, formula, kernel, handler); + assertThat(result.isSuccess()).isFalse(); } } diff --git a/src/test/java/com/booleworks/logicng/handlers/TimeoutMaxSATHandlerTest.java b/src/test/java/com/booleworks/logicng/handlers/TimeoutMaxSATHandlerTest.java index 9fc0e7d6..bd9b51fb 100644 --- a/src/test/java/com/booleworks/logicng/handlers/TimeoutMaxSATHandlerTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/TimeoutMaxSATHandlerTest.java @@ -9,9 +9,11 @@ import static com.booleworks.logicng.handlers.events.ComputationFinishedEvent.MAX_SAT_CALL_FINISHED; import static com.booleworks.logicng.handlers.events.ComputationStartedEvent.MAX_SAT_CALL_STARTED; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; @@ -78,6 +80,7 @@ public void testThatMethodsAreCalled() throws ParserException { solver.addSoftFormula(f.parse("~A"), weight); solver.addSoftFormula(f.parse("~B"), weight); final TimeoutHandler handler = Mockito.mock(TimeoutHandler.class); + when(handler.shouldResume(any())).thenReturn(true); solver.solve(handler); verify(handler, times(1)).shouldResume(eq(MAX_SAT_CALL_STARTED)); @@ -93,11 +96,8 @@ public void testTimeoutHandlerSingleTimeout() throws IOException { final int weight = solver.isWeighted() ? 2 : 1; formulas.forEach(c -> solver.addSoftFormula(c, weight)); final TimeoutHandler handler = new TimeoutHandler(10L); - - final MaxSAT.MaxSATResult solve = solver.solve(handler); - - assertThat(handler.isAborted()).isTrue(); - assertThat(solve).isEqualTo(MaxSAT.MaxSATResult.UNDEF); + final LNGResult solve = solver.solve(handler); + assertThat(solve.isSuccess()).isFalse(); } } @@ -108,11 +108,8 @@ public void testTimeoutHandlerFixedEnd() { final int weight = solver.isWeighted() ? 2 : 1; ph.forEach(c -> solver.addSoftFormula(c, weight)); final TimeoutHandler handler = new TimeoutHandler(System.currentTimeMillis() + 100L, FIXED_END); - - final MaxSAT.MaxSATResult solve = solver.solve(handler); - - assertThat(handler.isAborted()).isTrue(); - assertThat(solve).isEqualTo(MaxSAT.MaxSATResult.UNDEF); + final LNGResult solve = solver.solve(handler); + assertThat(solve.isSuccess()).isFalse(); } } } diff --git a/src/test/java/com/booleworks/logicng/handlers/TimeoutOptimizationHandlerTest.java b/src/test/java/com/booleworks/logicng/handlers/TimeoutOptimizationHandlerTest.java index 5e88ff3d..505d07d9 100644 --- a/src/test/java/com/booleworks/logicng/handlers/TimeoutOptimizationHandlerTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/TimeoutOptimizationHandlerTest.java @@ -12,10 +12,12 @@ import static com.booleworks.logicng.solvers.sat.SolverTestSet.SATSolverConfigParam.CNF_METHOD; import static com.booleworks.logicng.solvers.sat.SolverTestSet.SATSolverConfigParam.USE_AT_MOST_CLAUSES; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.booleworks.logicng.datastructures.Assignment; import com.booleworks.logicng.formulas.Formula; @@ -65,12 +67,8 @@ public void testThatMethodsAreCalled() throws ParserException { for (final SATSolver solver : solvers) { solver.add(formula); final TimeoutHandler handler = Mockito.mock(TimeoutHandler.class); - - solver.execute(OptimizationFunction.builder() - .handler(handler) - .literals(formula.variables(f)) - .maximize().build()); - + when(handler.shouldResume(any())).thenReturn(true); + solver.execute(OptimizationFunction.builder().literals(formula.variables(f)).maximize().build(), handler); verify(handler, times(1)).shouldResume(eq(OPTIMIZATION_FUNCTION_STARTED)); verify(handler, atLeast(1)).shouldResume(eq(SAT_CALL_STARTED)); } @@ -82,14 +80,12 @@ public void testTimeoutHandlerSingleTimeout() throws IOException { DimacsReader.readCNF(f, "src/test/resources/sat/too_large_gr_rcs_w5.shuffled.cnf"); for (final SATSolver solver : solvers) { solver.add(formulas); - final TimeoutHandler handler = new TimeoutHandler(100L); + final TimeoutHandler handler = new TimeoutHandler(10L); - final Assignment result = solver.execute(OptimizationFunction.builder() - .handler(handler) + final LNGResult> result = solver.execute(OptimizationFunction.builder() .literals(FormulaHelper.variables(f, formulas)) - .maximize().build()); - - assertThat(result).isNull(); + .maximize().build(), handler); + assertThat(result.isSuccess()).isFalse(); } } @@ -99,15 +95,11 @@ public void testTimeoutHandlerFixedEnd() throws IOException { DimacsReader.readCNF(f, "src/test/resources/sat/too_large_gr_rcs_w5.shuffled.cnf"); for (final SATSolver solver : solvers) { solver.add(formulas); - final TimeoutHandler handler = - new TimeoutHandler(100L, FIXED_END); - - final Assignment result = solver.execute(OptimizationFunction.builder() - .handler(handler) + final TimeoutHandler handler = new TimeoutHandler(100L, FIXED_END); + final LNGResult> result = solver.execute(OptimizationFunction.builder() .literals(FormulaHelper.variables(f, formulas)) - .maximize().build()); - - assertThat(result).isNull(); + .maximize().build(), handler); + assertThat(result.isSuccess()).isFalse(); } } } diff --git a/src/test/java/com/booleworks/logicng/handlers/TimeoutSATHandlerTest.java b/src/test/java/com/booleworks/logicng/handlers/TimeoutSATHandlerTest.java index 1a65d728..20b0875f 100644 --- a/src/test/java/com/booleworks/logicng/handlers/TimeoutSATHandlerTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/TimeoutSATHandlerTest.java @@ -15,11 +15,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.solvers.SATSolver; @@ -63,9 +63,8 @@ public void testThatMethodsAreCalled() throws ParserException { for (final SATSolver solver : solvers) { solver.add(f.parse("(x => y) & (~x => y) & (y => z) & (z => ~y)")); final TimeoutHandler handler = Mockito.mock(TimeoutHandler.class); - + when(handler.shouldResume(any())).thenReturn(true); solver.satCall().handler(handler).solve().close(); - verify(handler, times(1)).shouldResume(eq(SAT_CALL_STARTED)); verify(handler, atLeast(1)).shouldResume(eq(SAT_CONFLICT_DETECTED)); verify(handler, times(1)).shouldResume(eq(SAT_CALL_FINISHED)); @@ -79,15 +78,13 @@ public void testThatDetectedConflictIsHandledProperly() { final TimeoutHandler handler = Mockito.mock(TimeoutHandler.class); final AtomicInteger count = new AtomicInteger(0); when(handler.shouldResume(any())).thenReturn(true); - when(handler.shouldResume(eq(SAT_CONFLICT_DETECTED))).thenAnswer(invocationOnMock -> count.addAndGet(1) < 5); - - final Tristate result = solver.satCall().handler(handler).sat(); - - assertThat(result).isEqualTo(Tristate.UNDEF); - + when(handler.shouldResume(eq(SAT_CONFLICT_DETECTED))) + .thenAnswer(invocationOnMock -> count.addAndGet(1) < 5); + final LNGResult result = solver.satCall().handler(handler).sat(); + assertThat(result.isSuccess()).isFalse(); verify(handler, times(1)).shouldResume(eq(SAT_CALL_STARTED)); verify(handler, times(5)).shouldResume(eq(SAT_CONFLICT_DETECTED)); - verify(handler, times(1)).shouldResume(eq(SAT_CALL_FINISHED)); + verify(handler, never()).shouldResume(eq(SAT_CALL_FINISHED)); } } @@ -96,11 +93,8 @@ public void testTimeoutHandlerSingleTimeout() { for (final SATSolver solver : solvers) { solver.add(pg.generate(10)); final TimeoutHandler handler = new TimeoutHandler(100L); - - final Tristate result = solver.satCall().handler(handler).sat(); - - assertThat(handler.aborted).isTrue(); - assertThat(result).isEqualTo(Tristate.UNDEF); + final LNGResult result = solver.satCall().handler(handler).sat(); + assertThat(result.isSuccess()).isFalse(); } } @@ -108,13 +102,9 @@ public void testTimeoutHandlerSingleTimeout() { public void testTimeoutHandlerFixedEnd() { for (final SATSolver solver : solvers) { solver.add(pg.generate(10)); - final TimeoutHandler handler = - new TimeoutHandler(System.currentTimeMillis() + 100L, FIXED_END); - - final Tristate result = solver.satCall().handler(handler).sat(); - - assertThat(handler.aborted).isTrue(); - assertThat(result).isEqualTo(Tristate.UNDEF); + final TimeoutHandler handler = new TimeoutHandler(System.currentTimeMillis() + 100L, FIXED_END); + final LNGResult result = solver.satCall().handler(handler).sat(); + assertThat(result.isSuccess()).isFalse(); } } } diff --git a/src/test/java/com/booleworks/logicng/handlers/TimerTypeTest.java b/src/test/java/com/booleworks/logicng/handlers/TimerTypeTest.java index b72b42ec..3c2ff4b0 100644 --- a/src/test/java/com/booleworks/logicng/handlers/TimerTypeTest.java +++ b/src/test/java/com/booleworks/logicng/handlers/TimerTypeTest.java @@ -7,6 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; +import com.booleworks.logicng.handlers.events.SimpleEvent; import org.junit.jupiter.api.Test; public class TimerTypeTest { @@ -17,35 +18,35 @@ public class TimerTypeTest { public void testSingleTimeout() throws InterruptedException { final TimeoutHandler handler = handler(100L, TimeoutHandler.TimerType.SINGLE_TIMEOUT); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isFalse(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isTrue(); Thread.sleep(200L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } @Test public void testRestartingTimeout() throws InterruptedException { final TimeoutHandler handler = handler(100L, TimeoutHandler.TimerType.RESTARTING_TIMEOUT); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isFalse(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isTrue(); Thread.sleep(200L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isFalse(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isTrue(); Thread.sleep(200L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } @Test public void testFixedEnd() throws InterruptedException { final TimeoutHandler handler = fixedEndHandler(100L); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isFalse(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isTrue(); Thread.sleep(200L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } @Test @@ -53,25 +54,25 @@ public void testFixedEndWithDelayedStartedCall() throws InterruptedException { final TimeoutHandler handler = fixedEndHandler(100L); Thread.sleep(200L); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } @Test public void testFixedEndWithZeroTime() { final TimeoutHandler handler = fixedEndHandler(0L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } @Test public void testFixedEndWithPastPointInTime() { final TimeoutHandler handler = fixedEndHandler(-100L); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); handler.shouldResume(COMPUTATION_STARTED); - assertThat(handler.isAborted()).isTrue(); + assertThat(handler.shouldResume(SimpleEvent.NO_EVENT)).isFalse(); } private static TimeoutHandler handler(final long timeout, final TimeoutHandler.TimerType type) { diff --git a/src/test/java/com/booleworks/logicng/io/parsers/PropositionalParserTest.java b/src/test/java/com/booleworks/logicng/io/parsers/PropositionalParserTest.java index c8919648..ab19dcb5 100644 --- a/src/test/java/com/booleworks/logicng/io/parsers/PropositionalParserTest.java +++ b/src/test/java/com/booleworks/logicng/io/parsers/PropositionalParserTest.java @@ -12,7 +12,6 @@ import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class PropositionalParserTest extends TestWithExampleFormulas { @@ -20,100 +19,100 @@ public class PropositionalParserTest extends TestWithExampleFormulas { @Test public void testExceptions() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse((String) null)).isEqualTo(f.verum()); + assertThat(parser.parse("")).isEqualTo(f.verum()); + assertThat(parser.parse((String) null)).isEqualTo(f.verum()); } @Test public void testParseConstants() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("$true")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse("$false")).isEqualTo(f.falsum()); + assertThat(parser.parse("$true")).isEqualTo(f.verum()); + assertThat(parser.parse("$false")).isEqualTo(f.falsum()); } @Test public void testParseLiterals() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("A")).isEqualTo(f.variable("A")); - Assertions.assertThat(parser.parse("a")).isEqualTo(f.variable("a")); - Assertions.assertThat(parser.parse("a1")).isEqualTo(f.variable("a1")); - Assertions.assertThat(parser.parse("aA_Bb_Cc_12_3")).isEqualTo(f.variable("aA_Bb_Cc_12_3")); - Assertions.assertThat(parser.parse("~A")).isEqualTo(f.literal("A", false)); - Assertions.assertThat(parser.parse("~a")).isEqualTo(f.literal("a", false)); - Assertions.assertThat(parser.parse("~aA_Bb_Cc_12_3")).isEqualTo(f.literal("aA_Bb_Cc_12_3", false)); - Assertions.assertThat(parser.parse("#")).isEqualTo(f.literal("#", true)); - Assertions.assertThat(parser.parse("~#")).isEqualTo(f.literal("#", false)); - Assertions.assertThat(parser.parse("~A#B")).isEqualTo(f.literal("A#B", false)); - Assertions.assertThat(parser.parse("A#B")).isEqualTo(f.literal("A#B", true)); - Assertions.assertThat(parser.parse("~A#B")).isEqualTo(f.literal("A#B", false)); - Assertions.assertThat(parser.parse("#A#B_")).isEqualTo(f.literal("#A#B_", true)); - Assertions.assertThat(parser.parse("~#A#B_")).isEqualTo(f.literal("#A#B_", false)); + assertThat(parser.parse("A")).isEqualTo(f.variable("A")); + assertThat(parser.parse("a")).isEqualTo(f.variable("a")); + assertThat(parser.parse("a1")).isEqualTo(f.variable("a1")); + assertThat(parser.parse("aA_Bb_Cc_12_3")).isEqualTo(f.variable("aA_Bb_Cc_12_3")); + assertThat(parser.parse("~A")).isEqualTo(f.literal("A", false)); + assertThat(parser.parse("~a")).isEqualTo(f.literal("a", false)); + assertThat(parser.parse("~aA_Bb_Cc_12_3")).isEqualTo(f.literal("aA_Bb_Cc_12_3", false)); + assertThat(parser.parse("#")).isEqualTo(f.literal("#", true)); + assertThat(parser.parse("~#")).isEqualTo(f.literal("#", false)); + assertThat(parser.parse("~A#B")).isEqualTo(f.literal("A#B", false)); + assertThat(parser.parse("A#B")).isEqualTo(f.literal("A#B", true)); + assertThat(parser.parse("~A#B")).isEqualTo(f.literal("A#B", false)); + assertThat(parser.parse("#A#B_")).isEqualTo(f.literal("#A#B_", true)); + assertThat(parser.parse("~#A#B_")).isEqualTo(f.literal("#A#B_", false)); } @Test public void testParseOperators() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("~a")).isEqualTo(f.not(f.variable("a"))); - Assertions.assertThat(parser.parse("~Var")).isEqualTo(f.not(f.variable("Var"))); - Assertions.assertThat(parser.parse("a & b")).isEqualTo(f.and(f.variable("a"), f.variable("b"))); - Assertions.assertThat(parser.parse("~a & ~b")).isEqualTo(f.and(f.literal("a", false), f.literal("b", false))); - Assertions.assertThat(parser.parse("~a & b & ~c & d")) + assertThat(parser.parse("~a")).isEqualTo(f.not(f.variable("a"))); + assertThat(parser.parse("~Var")).isEqualTo(f.not(f.variable("Var"))); + assertThat(parser.parse("a & b")).isEqualTo(f.and(f.variable("a"), f.variable("b"))); + assertThat(parser.parse("~a & ~b")).isEqualTo(f.and(f.literal("a", false), f.literal("b", false))); + assertThat(parser.parse("~a & b & ~c & d")) .isEqualTo(f.and(f.literal("a", false), f.variable("b"), f.literal("c", false), f.variable("d"))); - Assertions.assertThat(parser.parse("a | b")).isEqualTo(f.or(f.variable("a"), f.variable("b"))); - Assertions.assertThat(parser.parse("~a | ~b")).isEqualTo(f.or(f.literal("a", false), f.literal("b", false))); - Assertions.assertThat(parser.parse("~a | b | ~c | d")) + assertThat(parser.parse("a | b")).isEqualTo(f.or(f.variable("a"), f.variable("b"))); + assertThat(parser.parse("~a | ~b")).isEqualTo(f.or(f.literal("a", false), f.literal("b", false))); + assertThat(parser.parse("~a | b | ~c | d")) .isEqualTo(f.or(f.literal("a", false), f.variable("b"), f.literal("c", false), f.variable("d"))); - Assertions.assertThat(parser.parse("a => b")).isEqualTo(f.implication(f.variable("a"), f.variable("b"))); - Assertions.assertThat(parser.parse("~a => ~b")) + assertThat(parser.parse("a => b")).isEqualTo(f.implication(f.variable("a"), f.variable("b"))); + assertThat(parser.parse("~a => ~b")) .isEqualTo(f.implication(f.literal("a", false), f.literal("b", false))); - Assertions.assertThat(parser.parse("a <=> b")).isEqualTo(f.equivalence(f.variable("a"), f.variable("b"))); - Assertions.assertThat(parser.parse("~a <=> ~b")) + assertThat(parser.parse("a <=> b")).isEqualTo(f.equivalence(f.variable("a"), f.variable("b"))); + assertThat(parser.parse("~a <=> ~b")) .isEqualTo(f.equivalence(f.literal("a", false), f.literal("b", false))); } @Test public void testParseMultiplication() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("13 * abc = 4")) + assertThat(parser.parse("13 * abc = 4")) .isEqualTo(f.pbc(CType.EQ, 4, new Literal[]{f.variable("abc")}, new int[]{13})); - Assertions.assertThat(parser.parse("-13 * a = 4")) + assertThat(parser.parse("-13 * a = 4")) .isEqualTo(f.pbc(CType.EQ, 4, new Literal[]{f.variable("a")}, new int[]{-13})); - Assertions.assertThat(parser.parse("13 * ~abc = -442")) + assertThat(parser.parse("13 * ~abc = -442")) .isEqualTo(f.pbc(CType.EQ, -442, new Literal[]{f.literal("abc", false)}, new int[]{13})); - Assertions.assertThat(parser.parse("-13 * ~a = -442")) + assertThat(parser.parse("-13 * ~a = -442")) .isEqualTo(f.pbc(CType.EQ, -442, new Literal[]{f.literal("a", false)}, new int[]{-13})); - Assertions.assertThat(parser.parse("13 * abc = 4")) + assertThat(parser.parse("13 * abc = 4")) .isEqualTo(f.pbc(CType.EQ, 4, new Literal[]{f.variable("abc")}, new int[]{13})); - Assertions.assertThat(parser.parse("13 * abc > 4")) + assertThat(parser.parse("13 * abc > 4")) .isEqualTo(f.pbc(CType.GT, 4, new Literal[]{f.variable("abc")}, new int[]{13})); - Assertions.assertThat(parser.parse("13 * abc >= 4")) + assertThat(parser.parse("13 * abc >= 4")) .isEqualTo(f.pbc(CType.GE, 4, new Literal[]{f.variable("abc")}, new int[]{13})); - Assertions.assertThat(parser.parse("13 * abc < 4")) + assertThat(parser.parse("13 * abc < 4")) .isEqualTo(f.pbc(CType.LT, 4, new Literal[]{f.variable("abc")}, new int[]{13})); - Assertions.assertThat(parser.parse("13 * abc <= 4")) + assertThat(parser.parse("13 * abc <= 4")) .isEqualTo(f.pbc(CType.LE, 4, new Literal[]{f.variable("abc")}, new int[]{13})); } @Test public void testParseAddition() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("4 * c + -4 * ~d < -4")).isEqualTo( + assertThat(parser.parse("4 * c + -4 * ~d < -4")).isEqualTo( f.pbc(CType.LT, -4, new Literal[]{f.variable("c"), f.literal("d", false)}, new int[]{4, -4})); - Assertions.assertThat(parser.parse("5 * c + -5 * ~c >= -5")).isEqualTo( + assertThat(parser.parse("5 * c + -5 * ~c >= -5")).isEqualTo( f.pbc(CType.GE, -5, new Literal[]{f.variable("c"), f.literal("c", false)}, new int[]{5, -5})); - Assertions.assertThat(parser.parse("6 * a + -6 * ~b + 12 * ~c > -6")).isEqualTo(f.pbc(CType.GT, -6, + assertThat(parser.parse("6 * a + -6 * ~b + 12 * ~c > -6")).isEqualTo(f.pbc(CType.GT, -6, new Literal[]{f.variable("a"), f.literal("b", false), f.literal("c", false)}, new int[]{6, -6, 12})); - Assertions.assertThat(parser.parse("c + -4 * ~d < -4")).isEqualTo( + assertThat(parser.parse("c + -4 * ~d < -4")).isEqualTo( f.pbc(CType.LT, -4, new Literal[]{f.variable("c"), f.literal("d", false)}, new int[]{1, -4})); - Assertions.assertThat(parser.parse("5 * c + ~c >= -5")) + assertThat(parser.parse("5 * c + ~c >= -5")) .isEqualTo(f.pbc(CType.GE, -5, new Literal[]{f.variable("c"), f.literal("c", false)}, new int[]{5, 1})); - Assertions.assertThat(parser.parse("c + d >= -5")) + assertThat(parser.parse("c + d >= -5")) .isEqualTo(f.pbc(CType.GE, -5, new Literal[]{f.variable("c"), f.literal("d", true)}, new int[]{1, 1})); - Assertions.assertThat(parser.parse("~c + ~d >= -5")).isEqualTo( + assertThat(parser.parse("~c + ~d >= -5")).isEqualTo( f.pbc(CType.GE, -5, new Literal[]{f.literal("c", false), f.literal("d", false)}, new int[]{1, 1})); - Assertions.assertThat(parser.parse("~c = -5")) + assertThat(parser.parse("~c = -5")) .isEqualTo(f.pbc(CType.EQ, -5, new Literal[]{f.literal("c", false)}, new int[]{1})); - Assertions.assertThat(parser.parse("~(c = -5)")) + assertThat(parser.parse("~(c = -5)")) .isEqualTo(f.not(f.pbc(CType.EQ, -5, new Literal[]{f.literal("c", true)}, new int[]{1}))); } @@ -122,92 +121,92 @@ public void testCombination() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); final Formula pbc = f.pbc(CType.GT, -6, new Literal[]{f.variable("a"), f.literal("b", false), f.literal("c", false)}, new int[]{6, -6, 12}); - Assertions.assertThat(parser.parse("(x => y & z) & (6 * a + -6 * ~b + 12 * ~c > -6)")) + assertThat(parser.parse("(x => y & z) & (6 * a + -6 * ~b + 12 * ~c > -6)")) .isEqualTo(f.and(f.implication(f.variable("x"), f.and(f.variable("y"), f.variable("z"))), pbc)); - Assertions.assertThat(parser.parse("~(6 * a - 6 * ~b - -12 * ~c > -6)")).isEqualTo(f.not(pbc)); + assertThat(parser.parse("~(6 * a - 6 * ~b - -12 * ~c > -6)")).isEqualTo(f.not(pbc)); } @Test public void testParsePrecedences() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("x | y & z")) + assertThat(parser.parse("x | y & z")) .isEqualTo(f.or(f.variable("x"), f.and(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x & y | z")) + assertThat(parser.parse("x & y | z")) .isEqualTo(f.or(f.and(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x => y & z")) + assertThat(parser.parse("x => y & z")) .isEqualTo(f.implication(f.variable("x"), f.and(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x & y => z")) + assertThat(parser.parse("x & y => z")) .isEqualTo(f.implication(f.and(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x <=> y & z")) + assertThat(parser.parse("x <=> y & z")) .isEqualTo(f.equivalence(f.variable("x"), f.and(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x & y <=> z")) + assertThat(parser.parse("x & y <=> z")) .isEqualTo(f.equivalence(f.and(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x => y | z")) + assertThat(parser.parse("x => y | z")) .isEqualTo(f.implication(f.variable("x"), f.or(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x | y => z")) + assertThat(parser.parse("x | y => z")) .isEqualTo(f.implication(f.or(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x <=> y | z")) + assertThat(parser.parse("x <=> y | z")) .isEqualTo(f.equivalence(f.variable("x"), f.or(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x | y <=> z")) + assertThat(parser.parse("x | y <=> z")) .isEqualTo(f.equivalence(f.or(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x => y => z")) + assertThat(parser.parse("x => y => z")) .isEqualTo(f.implication(f.variable("x"), f.implication(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x <=> y <=> z")) + assertThat(parser.parse("x <=> y <=> z")) .isEqualTo(f.equivalence(f.variable("x"), f.equivalence(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("(x | y) & z")) + assertThat(parser.parse("(x | y) & z")) .isEqualTo(f.and(f.or(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x & (y | z)")) + assertThat(parser.parse("x & (y | z)")) .isEqualTo(f.and(f.variable("x"), f.or(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("(x => y) & z")) + assertThat(parser.parse("(x => y) & z")) .isEqualTo(f.and(f.implication(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x & (y => z)")) + assertThat(parser.parse("x & (y => z)")) .isEqualTo(f.and(f.variable("x"), f.implication(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("(x => y) | z")) + assertThat(parser.parse("(x => y) | z")) .isEqualTo(f.or(f.implication(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x | (y => z)")) + assertThat(parser.parse("x | (y => z)")) .isEqualTo(f.or(f.variable("x"), f.implication(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("(x <=> y) & z")) + assertThat(parser.parse("(x <=> y) & z")) .isEqualTo(f.and(f.equivalence(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x & (y <=> z)")) + assertThat(parser.parse("x & (y <=> z)")) .isEqualTo(f.and(f.variable("x"), f.equivalence(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("(x <=> y) | z")) + assertThat(parser.parse("(x <=> y) | z")) .isEqualTo(f.or(f.equivalence(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x | (y <=> z)")) + assertThat(parser.parse("x | (y <=> z)")) .isEqualTo(f.or(f.variable("x"), f.equivalence(f.variable("y"), f.variable("z")))); - Assertions.assertThat(parser.parse("x => y <=> z")) + assertThat(parser.parse("x => y <=> z")) .isEqualTo(f.equivalence(f.implication(f.variable("x"), f.variable("y")), f.variable("z"))); - Assertions.assertThat(parser.parse("x => (y <=> z)")) + assertThat(parser.parse("x => (y <=> z)")) .isEqualTo(f.implication(f.variable("x"), f.equivalence(f.variable("y"), f.variable("z")))); } @Test public void parseEmptyString() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("")).isEqualTo(f.verum()); + assertThat(parser.parse("")).isEqualTo(f.verum()); } @Test public void testSkipSymbols() throws ParserException { final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse(" ")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse("\t")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse("\n")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse("\r")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse(" \r\n\n \t")).isEqualTo(f.verum()); - Assertions.assertThat(parser.parse("a\n&\tb")).isEqualTo(AND1); - Assertions.assertThat(parser.parse(" a\r=>\t\tb")).isEqualTo(IMP1); - Assertions.assertThat(parser.parse(" 2\n*a\r+\n\n-4*\tb +3*x=2")).isEqualTo(PBC1); + assertThat(parser.parse(" ")).isEqualTo(f.verum()); + assertThat(parser.parse("\t")).isEqualTo(f.verum()); + assertThat(parser.parse("\n")).isEqualTo(f.verum()); + assertThat(parser.parse("\r")).isEqualTo(f.verum()); + assertThat(parser.parse(" \r\n\n \t")).isEqualTo(f.verum()); + assertThat(parser.parse("a\n&\tb")).isEqualTo(AND1); + assertThat(parser.parse(" a\r=>\t\tb")).isEqualTo(IMP1); + assertThat(parser.parse(" 2\n*a\r+\n\n-4*\tb +3*x=2")).isEqualTo(PBC1); } @Test public void testNumberLiterals() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser parser = new PropositionalParser(f); - Assertions.assertThat(parser.parse("12 & A")).isEqualTo(f.and(f.variable("12"), f.variable("A"))); - Assertions.assertThat(parser.parse("~12 & A")).isEqualTo(f.and(f.literal("12", false), f.variable("A"))); - Assertions.assertThat(parser.parse("12 * 12 + 13 * A + 10 * B <= 25")).isEqualTo(f.pbc(CType.LE, 25, + assertThat(parser.parse("12 & A")).isEqualTo(f.and(f.variable("12"), f.variable("A"))); + assertThat(parser.parse("~12 & A")).isEqualTo(f.and(f.literal("12", false), f.variable("A"))); + assertThat(parser.parse("12 * 12 + 13 * A + 10 * B <= 25")).isEqualTo(f.pbc(CType.LE, 25, new Literal[]{f.variable("12"), f.variable("A"), f.variable("B")}, new int[]{12, 13, 10})); - Assertions.assertThat(parser.parse("-12 * ~12 + 13 * A + 10 * B <= 25")).isEqualTo(f.pbc(CType.LE, 25, + assertThat(parser.parse("-12 * ~12 + 13 * A + 10 * B <= 25")).isEqualTo(f.pbc(CType.LE, 25, new Literal[]{f.literal("12", false), f.variable("A"), f.variable("B")}, new int[]{-12, 13, 10})); } diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDOperationsTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDOperationsTest.java index fb89549a..35522006 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDOperationsTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDOperationsTest.java @@ -98,8 +98,8 @@ public void testRestriction() throws ParserException { final Literal a = f.literal("A", true); final List resNotA = Collections.singletonList(f.literal("A", false)); final List resAB = Arrays.asList(f.literal("A", true), f.literal("B", true)); - Assertions.assertThat(bddPosLit.construction.restrict(0, 1)).isEqualTo(0); - Assertions.assertThat(bddPosLit.construction.restrict(1, 1)).isEqualTo(1); + assertThat(bddPosLit.construction.restrict(0, 1)).isEqualTo(0); + assertThat(bddPosLit.construction.restrict(1, 1)).isEqualTo(1); assertThat(bddVerum.restrict(a)).isEqualTo(bddVerum); assertThat(bddVerum.restrict(resNotA)).isEqualTo(bddVerum); assertThat(bddVerum.restrict(resAB)).isEqualTo(bddVerum); @@ -130,8 +130,8 @@ public void testRestriction() throws ParserException { public void testExistentialQuantification() throws ParserException { final Variable a = f.variable("A"); final List resAB = Arrays.asList(f.variable("A"), f.variable("B")); - Assertions.assertThat(bddPosLit.construction.exists(0, 1)).isEqualTo(0); - Assertions.assertThat(bddPosLit.construction.exists(1, 1)).isEqualTo(1); + assertThat(bddPosLit.construction.exists(0, 1)).isEqualTo(0); + assertThat(bddPosLit.construction.exists(1, 1)).isEqualTo(1); assertThat(bddVerum.exists(a)).isEqualTo(bddVerum); assertThat(bddVerum.exists(resAB)).isEqualTo(bddVerum); assertThat(bddFalsum.exists(a)).isEqualTo(bddFalsum); @@ -154,8 +154,8 @@ public void testExistentialQuantification() throws ParserException { public void testUniversalQuantification() throws ParserException { final Variable a = f.variable("A"); final List resAB = Arrays.asList(f.variable("A"), f.variable("B")); - Assertions.assertThat(bddPosLit.construction.forAll(0, 1)).isEqualTo(0); - Assertions.assertThat(bddPosLit.construction.forAll(1, 1)).isEqualTo(1); + assertThat(bddPosLit.construction.forAll(0, 1)).isEqualTo(0); + assertThat(bddPosLit.construction.forAll(1, 1)).isEqualTo(1); assertThat(bddVerum.forall(a)).isEqualTo(bddVerum); assertThat(bddVerum.forall(resAB)).isEqualTo(bddVerum); assertThat(bddFalsum.forall(a)).isEqualTo(bddFalsum); diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDReorderingTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDReorderingTest.java index 017e662c..6b3a6605 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDReorderingTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/BDDReorderingTest.java @@ -89,7 +89,7 @@ public void testSwapping(final FormulaContext _c) throws ParserException { bdd.swapVariables(_c.b, _c.c); assertThat(bdd.getVariableOrder()).containsExactly(_c.b, _c.c, _c.a); assertThat(_c.f.equivalence(formula, bdd.cnf()).holds(new TautologyPredicate(_c.f))).isTrue(); - Assertions.assertThat(bdd.apply(new LngBDDFunction(_c.f))).isEqualTo( + assertThat(bdd.apply(new LngBDDFunction(_c.f))).isEqualTo( new BDDInnerNode(_c.b, new BDDInnerNode(_c.c, new BDDInnerNode(_c.a, BDDConstant.getFalsumNode(_c.f), BDDConstant.getVerumNode(_c.f)), @@ -108,13 +108,13 @@ public void testSwappingMultipleBdds(final FormulaContext _c) throws ParserExcep final BDD bdd2 = BDDFactory.build(_c.f, formula2, kernel); assertThat(bdd1.getVariableOrder()).containsExactly(_c.a, _c.b, _c.c); assertThat(bdd2.getVariableOrder()).containsExactly(_c.a, _c.b, _c.c); - Assertions.assertThat(bdd2.apply(new LngBDDFunction(_c.f))).isEqualTo( + assertThat(bdd2.apply(new LngBDDFunction(_c.f))).isEqualTo( new BDDInnerNode(_c.a, BDDConstant.getFalsumNode(_c.f), new BDDInnerNode(_c.b, BDDConstant.getFalsumNode(_c.f), BDDConstant.getVerumNode(_c.f)))); bdd1.swapVariables(_c.a, _c.b); assertThat(bdd1.getVariableOrder()).containsExactly(_c.b, _c.a, _c.c); assertThat(bdd2.getVariableOrder()).containsExactly(_c.b, _c.a, _c.c); - Assertions.assertThat(bdd2.apply(new LngBDDFunction(_c.f))).isEqualTo( + assertThat(bdd2.apply(new LngBDDFunction(_c.f))).isEqualTo( new BDDInnerNode(_c.b, BDDConstant.getFalsumNode(_c.f), new BDDInnerNode(_c.a, BDDConstant.getFalsumNode(_c.f), BDDConstant.getVerumNode(_c.f)))); } diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/FormulaBDDTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/FormulaBDDTest.java index 7b6114fb..7d387934 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/FormulaBDDTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/FormulaBDDTest.java @@ -29,7 +29,7 @@ public void testSimpleCases() { bdd = f.falsum().bdd(f); assertThat(bdd.isContradiction()).isTrue(); bdd = f.variable("A").bdd(f); - Assertions.assertThat(bdd.enumerateAllModels()).containsExactly(new Model(f.variable("A"))); + assertThat(bdd.enumerateAllModels()).containsExactly(new Model(f.variable("A"))); } @Test @@ -67,8 +67,8 @@ public void testBDDGeneration() throws ParserException { @Test public void testNonNnfs() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); - Assertions.assertThat(f.parse("A + 2*B - C = 1").bdd(f)).isNotNull(); - Assertions.assertThat(f.parse("(A & B & C | D & E & F) & (A - 2*B -D <= 0) | (C + 3*D - F > 0)").bdd(f)) + assertThat(f.parse("A + 2*B - C = 1").bdd(f)).isNotNull(); + assertThat(f.parse("(A & B & C | D & E & F) & (A - 2*B -D <= 0) | (C + 3*D - F > 0)").bdd(f)) .isNotNull(); } } diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/LargeBDDTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/LargeBDDTest.java index d50e1b6e..162bc9b1 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/LargeBDDTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/LargeBDDTest.java @@ -9,13 +9,13 @@ import com.booleworks.logicng.LongRunningTag; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NumberOfNodesBDDHandler; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; import com.booleworks.logicng.testutils.NQueensGenerator; import com.booleworks.logicng.testutils.PigeonHoleGenerator; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.math.BigInteger; @@ -63,7 +63,7 @@ private void testQueens(final FormulaFactory f, final NQueensGenerator generator assertThat(cnf.isCNF(f)).isTrue(); final BDD cnfBDD = BDDFactory.build(f, cnf, kernel); assertThat(cnfBDD).isEqualTo(bdd); - Assertions.assertThat(bdd.support()).isEqualTo(queens.variables(f)); + assertThat(bdd.support()).isEqualTo(queens.variables(f)); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(models)); } @@ -74,9 +74,9 @@ public void testTimeoutHandlerNgSmall() { final Formula queens = generator.generate(4); final BDDKernel kernel = new BDDKernel(f, queens.variables(f).size(), 10000, 10000); final TimeoutHandler handler = new TimeoutHandler(2000L); - final BDD bdd = BDDFactory.build(f, queens, kernel, handler); - assertThat(handler.isAborted()).isFalse(); - assertThat(bdd.index()).isNotEqualTo(BDDKernel.BDD_ABORT); + final LNGResult bdd = BDDFactory.build(f, queens, kernel, handler); + assertThat(bdd.isSuccess()).isTrue(); + assertThat(bdd.getResult().index()).isNotEqualTo(BDDKernel.BDD_ABORT); } @Test @@ -87,9 +87,9 @@ public void testTimeoutHandlerNgLarge() { final Formula queens = generator.generate(10); final BDDKernel kernel = new BDDKernel(f, queens.variables(f).size(), 10000, 10000); final TimeoutHandler handler = new TimeoutHandler(1000L); - final BDD bdd = BDDFactory.build(f, queens, kernel, handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(bdd.index()).isEqualTo(BDDKernel.BDD_ABORT); + final LNGResult bdd = BDDFactory.build(f, queens, kernel, handler); + assertThat(bdd.isSuccess()).isFalse(); + assertThat(bdd.getResult()).isNull(); } @Test @@ -99,9 +99,9 @@ public void testNumberOfNodesHandlerSmall() { final Formula queens = generator.generate(4); final BDDKernel kernel = new BDDKernel(f, queens.variables(f).size(), 10000, 10000); final NumberOfNodesBDDHandler handler = new NumberOfNodesBDDHandler(1000); - final BDD bdd = BDDFactory.build(f, queens, kernel, handler); - assertThat(handler.isAborted()).isFalse(); - assertThat(bdd.index()).isNotEqualTo(BDDKernel.BDD_ABORT); + final LNGResult bdd = BDDFactory.build(f, queens, kernel, handler); + assertThat(bdd.isSuccess()).isTrue(); + assertThat(bdd.getResult().index()).isNotEqualTo(BDDKernel.BDD_ABORT); } @Test @@ -111,9 +111,9 @@ public void testNumberOfNodesHandlerLarge() { final Formula queens = generator.generate(10); final BDDKernel kernel = new BDDKernel(f, queens.variables(f).size(), 10000, 10000); final NumberOfNodesBDDHandler handler = new NumberOfNodesBDDHandler(5); - final BDD bdd = BDDFactory.build(f, queens, kernel, handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(bdd.index()).isEqualTo(BDDKernel.BDD_ABORT); + final LNGResult bdd = BDDFactory.build(f, queens, kernel, handler); + assertThat(bdd.isSuccess()).isFalse(); + assertThat(bdd.getResult()).isNull(); } @Test @@ -122,8 +122,8 @@ public void testNumberOfNodesHandler() throws ParserException { final Formula formula = f.parse("A <=> ~(B => C & F & G & ~H | A & D & ~E)"); final BDDKernel kernel = new BDDKernel(f, formula.variables(f).size(), 10000, 10000); final NumberOfNodesBDDHandler handler = new NumberOfNodesBDDHandler(5); - final BDD bdd = BDDFactory.build(f, formula, kernel, handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(bdd.index()).isEqualTo(BDDKernel.BDD_ABORT); + final LNGResult bdd = BDDFactory.build(f, formula, kernel, handler); + assertThat(bdd.isSuccess()).isFalse(); + assertThat(bdd.getResult()).isNull(); } } diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/SimpleBDDTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/SimpleBDDTest.java index 5f053301..fc4427c2 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/SimpleBDDTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/SimpleBDDTest.java @@ -11,7 +11,6 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.formulas.Variable; -import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.parsers.PropositionalParser; import com.booleworks.logicng.knowledgecompilation.bdds.datastructures.BDDConstant; @@ -35,27 +34,27 @@ public void testTrue(final FormulaContext _c) { assertThat(bdd.cnf()).isEqualTo(_c.f.verum()); assertThat(bdd.dnf()).isEqualTo(_c.f.verum()); assertThat(bdd.modelCount()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactly(new Model()); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ZERO); - Assertions.assertThat(bdd.toLngBdd()).isEqualTo(BDDConstant.getVerumNode(_c.f)); + assertThat(bdd.toLngBdd()).isEqualTo(BDDConstant.getVerumNode(_c.f)); } @ParameterizedTest @MethodSource("contexts") public void testFalse(final FormulaContext _c) { final BDDKernel kernel = new BDDKernel(_c.f, 0, 100, 100); - final BDD bdd = BDDFactory.build(_c.f, _c.f.falsum(), kernel, NopHandler.get()); + final BDD bdd = BDDFactory.build(_c.f, _c.f.falsum(), kernel); assertThat(bdd.isTautology()).isFalse(); assertThat(bdd.isContradiction()).isTrue(); assertThat(bdd.cnf()).isEqualTo(_c.f.falsum()); assertThat(bdd.dnf()).isEqualTo(_c.f.falsum()); assertThat(bdd.modelCount()).isEqualTo(BigInteger.ZERO); - Assertions.assertThat(bdd.underlyingKernel()).isSameAs(kernel); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel()).isSameAs(kernel); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).isEmpty(); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.toLngBdd()).isEqualTo(BDDConstant.getFalsumNode(_c.f)); + assertThat(bdd.toLngBdd()).isEqualTo(BDDConstant.getFalsumNode(_c.f)); } @ParameterizedTest @@ -67,10 +66,10 @@ public void testPositiveLiteral(final FormulaContext _c) { assertThat(bdd.cnf()).isEqualTo(_c.f.literal("A", true)); assertThat(bdd.dnf()).isEqualTo(_c.f.literal("A", true)); assertThat(bdd.modelCount()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactly(new Model(_c.f.literal("A", true))); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.toLngBdd().toString()).isEqualTo(" high=<$true>>"); + assertThat(bdd.toLngBdd().toString()).isEqualTo(" high=<$true>>"); } @ParameterizedTest @@ -82,10 +81,10 @@ public void testNegativeLiteral(final FormulaContext _c) { assertThat(bdd.cnf()).isEqualTo(_c.f.literal("A", false)); assertThat(bdd.dnf()).isEqualTo(_c.f.literal("A", false)); assertThat(bdd.modelCount()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactly(new Model(_c.f.literal("A", false))); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.toLngBdd().toString()).isEqualTo(" high=<$false>>"); + assertThat(bdd.toLngBdd().toString()).isEqualTo(" high=<$false>>"); } @ParameterizedTest @@ -97,14 +96,14 @@ public void testImplication(final FormulaContext _c) throws ParserException { assertThat(bdd.cnf()).isEqualTo(_c.p.parse("~A | ~B")); assertThat(bdd.dnf()).isEqualTo(_c.p.parse("~A | A & ~B")); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(3)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactlyInAnyOrder( new Model(_c.f.literal("A", false), _c.f.literal("B", false)), new Model(_c.f.literal("A", true), _c.f.literal("B", false)), new Model(_c.f.literal("A", false), _c.f.literal("B", true)) ); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.toLngBdd().toString()) + assertThat(bdd.toLngBdd().toString()) .isEqualTo(" high= high=<$false>>>"); } @@ -117,13 +116,13 @@ public void testEquivalence(final FormulaContext _c) throws ParserException { assertThat(bdd.cnf()).isEqualTo(_c.p.parse("(A | B) & (~A | ~B)")); assertThat(bdd.dnf()).isEqualTo(_c.p.parse("~A & B | A & ~B")); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(2)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactlyInAnyOrder( new Model(_c.f.literal("A", true), _c.f.literal("B", false)), new Model(_c.f.literal("A", false), _c.f.literal("B", true)) ); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.valueOf(2)); - Assertions.assertThat(bdd.toLngBdd().toString()) + assertThat(bdd.toLngBdd().toString()) .isEqualTo(" high=<$true>> high= high=<$false>>>"); } @@ -136,7 +135,7 @@ public void testOr(final FormulaContext _c) throws ParserException { assertThat(bdd.cnf()).isEqualTo(_c.p.parse("A | B | ~C")); assertThat(bdd.dnf()).isEqualTo(_c.p.parse("~A & ~B & ~C | ~A & B | A")); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(7)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(_c.f); assertThat(bdd.enumerateAllModels()).containsExactlyInAnyOrder( new Model(_c.f.literal("A", false), _c.f.literal("B", false), _c.f.literal("C", false)), new Model(_c.f.literal("A", false), _c.f.literal("B", true), _c.f.literal("C", false)), @@ -147,7 +146,7 @@ public void testOr(final FormulaContext _c) throws ParserException { new Model(_c.f.literal("A", true), _c.f.literal("B", true), _c.f.literal("C", true)) ); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.ONE); - Assertions.assertThat(bdd.toLngBdd().toString()) + assertThat(bdd.toLngBdd().toString()) .isEqualTo(" high=<$false>> high=<$true>> high=<$true>>"); } @@ -158,18 +157,18 @@ public void testAnd(final FormulaContext _c) throws ParserException { final PropositionalParser parser = new PropositionalParser(f); final List ordering = Arrays.asList(f.variable("A"), f.variable("B"), f.variable("C")); final BDDKernel kernel = new BDDKernel(f, ordering, 1000, 1000); - final BDD bdd = BDDFactory.build(f, parser.parse("A & B & ~C"), kernel, NopHandler.get()); + final BDD bdd = BDDFactory.build(f, parser.parse("A & B & ~C"), kernel); assertThat(bdd.isTautology()).isFalse(); assertThat(bdd.isContradiction()).isFalse(); assertThat(bdd.cnf()).isEqualTo(parser.parse("A & (~A | B) & (~A | ~B | ~C)")); assertThat(bdd.dnf()).isEqualTo(parser.parse("A & B & ~C")); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(1)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(f); assertThat(bdd.enumerateAllModels()).containsExactlyInAnyOrder( new Model(f.literal("A", true), f.literal("B", true), f.literal("C", false)) ); assertThat(bdd.numberOfClausesCNF()).isEqualTo(BigInteger.valueOf(3)); - Assertions.assertThat(bdd.toLngBdd().toString()) + assertThat(bdd.toLngBdd().toString()) .isEqualTo(" high= high= high=<$false>>>>"); } @@ -180,15 +179,15 @@ public void testFormula(final FormulaContext _c) throws ParserException { final PropositionalParser parser = new PropositionalParser(f); final List ordering = Arrays.asList(f.variable("A"), f.variable("B"), f.variable("C")); final BDDKernel kernel = new BDDKernel(f, ordering, 1000, 1000); - final BDD bdd = BDDFactory.build(f, parser.parse("(A => ~C) | (B & ~C)"), kernel, NopHandler.get()); + final BDD bdd = BDDFactory.build(f, parser.parse("(A => ~C) | (B & ~C)"), kernel); assertThat(bdd.isTautology()).isFalse(); assertThat(bdd.isContradiction()).isFalse(); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(6)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(f); assertThat(bdd.enumerateAllModels()).hasSize(6); assertThat(bdd.enumerateAllModels(f.variable("A"))).hasSize(2); assertThat(bdd.hashCode()) - .isEqualTo(BDDFactory.build(f, parser.parse("(A => ~C) | (B & ~C)"), kernel, NopHandler.get()).hashCode()); + .isEqualTo(BDDFactory.build(f, parser.parse("(A => ~C) | (B & ~C)"), kernel).hashCode()); assertThat(bdd.toString()).isEqualTo("BDD{8}"); } @@ -198,13 +197,13 @@ public void testCC(final FormulaContext _c) throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser parser = new PropositionalParser(f); final BDDKernel kernel = new BDDKernel(f, 3, 1000, 1000); - final BDD bdd = BDDFactory.build(f, parser.parse("A + B + C = 1"), kernel, NopHandler.get()); + final BDD bdd = BDDFactory.build(f, parser.parse("A + B + C = 1"), kernel); assertThat(bdd.isTautology()).isFalse(); assertThat(bdd.isContradiction()).isFalse(); assertThat(bdd.cnf()).isEqualTo(parser.parse("(A | B | C) & (A | ~B | ~C) & (~A | B | ~C) & (~A | ~B)")); assertThat(bdd.dnf()).isEqualTo(parser.parse("~A & ~B & C | ~A & B & ~C | A & ~B & ~C")); assertThat(bdd.modelCount()).isEqualTo(BigInteger.valueOf(3)); - Assertions.assertThat(bdd.underlyingKernel().factory()).isSameAs(f); + assertThat(bdd.underlyingKernel().factory()).isSameAs(f); assertThat(bdd.enumerateAllModels()).containsExactlyInAnyOrder( new Model(f.literal("A", true), f.literal("B", false), f.literal("C", false)), new Model(f.literal("A", false), f.literal("B", true), f.literal("C", false)), diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/datastructures/BDDNodeTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/datastructures/BDDNodeTest.java index 45151550..25548a08 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/datastructures/BDDNodeTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/datastructures/BDDNodeTest.java @@ -21,9 +21,9 @@ public void testSimpleMethods() { assertThat(verumNode.isInnerNode()).isFalse(); assertThat(falsumNode.isInnerNode()).isFalse(); assertThat(innerNode.isInnerNode()).isTrue(); - Assertions.assertThat(verumNode.label()).isEqualTo(f.verum()); - Assertions.assertThat(falsumNode.label()).isEqualTo(f.falsum()); - Assertions.assertThat(innerNode.label()).isEqualTo(f.variable("A")); + assertThat(verumNode.label()).isEqualTo(f.verum()); + assertThat(falsumNode.label()).isEqualTo(f.falsum()); + assertThat(innerNode.label()).isEqualTo(f.variable("A")); assertThat(verumNode.low()).isNull(); assertThat(verumNode.high()).isNull(); assertThat(falsumNode.low()).isNull(); diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/DFSOrderingTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/DFSOrderingTest.java index 712383a8..1db896c1 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/DFSOrderingTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/DFSOrderingTest.java @@ -21,20 +21,20 @@ public class DFSOrderingTest { public void testSimpleCases() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(ordering.getOrder(f, p.parse("$true"))).isEmpty(); - Assertions.assertThat(ordering.getOrder(f, p.parse("$false"))).isEmpty(); - Assertions.assertThat(ordering.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); - Assertions.assertThat(ordering.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("$true"))).isEmpty(); + assertThat(ordering.getOrder(f, p.parse("$false"))).isEmpty(); + assertThat(ordering.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); + assertThat(ordering.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(ordering.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(ordering.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(ordering.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(ordering.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(ordering.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), + assertThat(ordering.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); } diff --git a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/OccurrenceOrderingTest.java b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/OccurrenceOrderingTest.java index 2a0e3719..6239c221 100644 --- a/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/OccurrenceOrderingTest.java +++ b/src/test/java/com/booleworks/logicng/knowledgecompilation/bdds/orderings/OccurrenceOrderingTest.java @@ -4,11 +4,12 @@ package com.booleworks.logicng.knowledgecompilation.bdds.orderings; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.parsers.PropositionalParser; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class OccurrenceOrderingTest { @@ -20,20 +21,20 @@ public class OccurrenceOrderingTest { public void testSimpleCasesMin2Max() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(min2max.getOrder(f, p.parse("$true"))).isEmpty(); - Assertions.assertThat(min2max.getOrder(f, p.parse("$false"))).isEmpty(); - Assertions.assertThat(min2max.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); - Assertions.assertThat(min2max.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("$true"))).isEmpty(); + assertThat(min2max.getOrder(f, p.parse("$false"))).isEmpty(); + assertThat(min2max.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); + assertThat(min2max.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(min2max.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(min2max.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(min2max.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(min2max.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(min2max.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), + assertThat(min2max.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); } @@ -41,20 +42,20 @@ public void testSimpleCasesMin2Max() throws ParserException { public void testSimpleCasesMax2Min() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final PropositionalParser p = new PropositionalParser(f); - Assertions.assertThat(max2min.getOrder(f, p.parse("$true"))).isEmpty(); - Assertions.assertThat(max2min.getOrder(f, p.parse("$false"))).isEmpty(); - Assertions.assertThat(max2min.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); - Assertions.assertThat(max2min.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("$true"))).isEmpty(); + assertThat(max2min.getOrder(f, p.parse("$false"))).isEmpty(); + assertThat(max2min.getOrder(f, p.parse("A"))).containsExactly(f.variable("A")); + assertThat(max2min.getOrder(f, p.parse("A => ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(max2min.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("A <=> ~B"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(max2min.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("~(A <=> ~B)"))).containsExactly(f.variable("A"), f.variable("B")); - Assertions.assertThat(max2min.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("A | ~C | B | D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(max2min.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("A & ~C & B & D"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); - Assertions.assertThat(max2min.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), + assertThat(max2min.getOrder(f, p.parse("A + C + B + D < 2"))).containsExactly(f.variable("A"), f.variable("C"), f.variable("B"), f.variable("D")); } @@ -65,7 +66,7 @@ public void testComplexFormulaMin2Max() throws ParserException { final Formula formula = p.parse("(A => ~B) & ((A & C) | (D & ~C)) & (A | Y | X) & (Y <=> (X | (X + W + A + F < 1)))"); - Assertions.assertThat(min2max.getOrder(f, formula)).containsExactly( + assertThat(min2max.getOrder(f, formula)).containsExactly( f.variable("A"), f.variable("X"), f.variable("C"), @@ -84,7 +85,7 @@ public void testComplexFormulaMax2Min() throws ParserException { final Formula formula = p.parse("(A => ~B) & ((A & C) | (D & ~C)) & (A | Y | X) & (Y <=> (X | (X + W + A + F < 1)))"); - Assertions.assertThat(max2min.getOrder(f, formula)).containsExactly( + assertThat(max2min.getOrder(f, formula)).containsExactly( f.variable("B"), f.variable("D"), f.variable("W"), diff --git a/src/test/java/com/booleworks/logicng/np/SetCoverTest.java b/src/test/java/com/booleworks/logicng/np/SetCoverTest.java index f96c45dc..c7eb55e0 100644 --- a/src/test/java/com/booleworks/logicng/np/SetCoverTest.java +++ b/src/test/java/com/booleworks/logicng/np/SetCoverTest.java @@ -4,8 +4,9 @@ package com.booleworks.logicng.np; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.formulas.FormulaFactory; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -29,27 +30,27 @@ public void smallTest() { sets.add(new TreeSet<>(Arrays.asList("b", "e", "h", "k"))); sets.add(new TreeSet<>(Arrays.asList("c", "f", "i", "l"))); sets.add(new TreeSet<>(Arrays.asList("j", "k", "l"))); - Assertions.assertThat(SetCover.compute(f, sets)).containsExactlyInAnyOrder(sets.get(2), sets.get(3), + assertThat(SetCover.compute(f, sets)).containsExactlyInAnyOrder(sets.get(2), sets.get(3), sets.get(4)); } @Test public void cornerCasesTest() { final List> sets = new ArrayList<>(); - Assertions.assertThat(SetCover.compute(f, sets)).isEmpty(); + assertThat(SetCover.compute(f, sets)).isEmpty(); sets.add(Collections.emptySet()); - Assertions.assertThat(SetCover.compute(f, sets)).isEmpty(); + assertThat(SetCover.compute(f, sets)).isEmpty(); sets.add(new HashSet<>(Collections.singletonList("A"))); sets.add(new HashSet<>(Collections.singletonList("A"))); sets.add(new HashSet<>(Collections.singletonList("A"))); - Assertions.assertThat(SetCover.compute(f, sets)).hasSize(1); + assertThat(SetCover.compute(f, sets)).hasSize(1); sets.add(new HashSet<>(Collections.singletonList("B"))); - Assertions.assertThat(SetCover.compute(f, sets)).containsExactlyInAnyOrder( + assertThat(SetCover.compute(f, sets)).containsExactlyInAnyOrder( new HashSet<>(Collections.singletonList("A")), new HashSet<>(Collections.singletonList("B")) ); sets.add(new HashSet<>(Arrays.asList("A", "B"))); - Assertions.assertThat(SetCover.compute(f, sets)).hasSize(1).containsExactly( + assertThat(SetCover.compute(f, sets)).hasSize(1).containsExactly( new HashSet<>(Arrays.asList("A", "B")) ); } diff --git a/src/test/java/com/booleworks/logicng/predicates/satisfiability/PredicatesTest.java b/src/test/java/com/booleworks/logicng/predicates/satisfiability/PredicatesTest.java index fa29f13b..c686aa65 100644 --- a/src/test/java/com/booleworks/logicng/predicates/satisfiability/PredicatesTest.java +++ b/src/test/java/com/booleworks/logicng/predicates/satisfiability/PredicatesTest.java @@ -123,8 +123,8 @@ public void testSat(final FormulaContext _c) { assertThat(_c.or3.holds(sat)).isTrue(); assertThat(_c.not1.holds(sat)).isTrue(); assertThat(_c.not2.holds(sat)).isTrue(); - Assertions.assertThat(new PigeonHoleGenerator(_c.f).generate(1).holds(sat)).isFalse(); - Assertions.assertThat(new PigeonHoleGenerator(_c.f).generate(2).holds(sat)).isFalse(); - Assertions.assertThat(new PigeonHoleGenerator(_c.f).generate(3).holds(sat)).isFalse(); + assertThat(new PigeonHoleGenerator(_c.f).generate(1).holds(sat)).isFalse(); + assertThat(new PigeonHoleGenerator(_c.f).generate(2).holds(sat)).isFalse(); + assertThat(new PigeonHoleGenerator(_c.f).generate(3).holds(sat)).isFalse(); } } diff --git a/src/test/java/com/booleworks/logicng/primecomputation/PrimeCompilerTest.java b/src/test/java/com/booleworks/logicng/primecomputation/PrimeCompilerTest.java index f92082b9..1acee3b5 100644 --- a/src/test/java/com/booleworks/logicng/primecomputation/PrimeCompilerTest.java +++ b/src/test/java/com/booleworks/logicng/primecomputation/PrimeCompilerTest.java @@ -19,6 +19,7 @@ import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.BoundedOptimizationHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.FormulaReader; @@ -230,14 +231,13 @@ private void verifyImplicates(final List> implicateSets, fina } private void testHandler(final ComputationHandler handler, final Formula formula, final PrimeCompiler compiler, - final PrimeResult.CoverageType coverageType, - final boolean expAborted) { - final PrimeResult result = compiler.compute(formula.factory(), formula, coverageType, handler); - assertThat(handler.isAborted()).isEqualTo(expAborted); + final PrimeResult.CoverageType coverageType, final boolean expAborted) { + final LNGResult result = compiler.compute(formula.factory(), formula, coverageType, handler); + assertThat(!result.isSuccess()).isEqualTo(expAborted); if (expAborted) { - assertThat(result).isNull(); + assertThat(result.getResult()).isNull(); } else { - assertThat(result).isNotNull(); + assertThat(result.getResult()).isNotNull(); } } } diff --git a/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicantReductionTest.java b/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicantReductionTest.java index 81e3afc6..16e630c8 100644 --- a/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicantReductionTest.java +++ b/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicantReductionTest.java @@ -8,7 +8,6 @@ import com.booleworks.logicng.LongRunningTag; import com.booleworks.logicng.RandomTag; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.FormulaFactory; @@ -16,6 +15,7 @@ import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.BoundedSatHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.FormulaReader; @@ -24,7 +24,6 @@ import com.booleworks.logicng.util.FormulaCornerCases; import com.booleworks.logicng.util.FormulaRandomizer; import com.booleworks.logicng.util.FormulaRandomizerConfig; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -137,19 +136,18 @@ private void testFormula(final Formula formula, final ComputationHandler handler final SATSolver solver = SATSolver.newSolver(f); solver.add(formula); try (final SATCall call = solver.satCall().solve()) { - final boolean isSAT = call.getSatResult() == Tristate.TRUE; - if (!isSAT) { + if (!call.getSatResult().getResult()) { return; } final SortedSet model = call.model(formula.variables(f)).literals(); final NaivePrimeReduction naive = new NaivePrimeReduction(f, formula); - final SortedSet primeImplicant = naive.reduceImplicant(model, handler); + final LNGResult> primeImplicant = naive.reduceImplicant(model, handler); if (expAborted) { - assertThat(handler.isAborted()).isTrue(); - assertThat(primeImplicant).isNull(); + assertThat(primeImplicant.isSuccess()).isFalse(); + assertThat(primeImplicant.getResult()).isNull(); } else { - assertThat(model).containsAll(primeImplicant); - testPrimeImplicantProperty(formula, primeImplicant); + assertThat(model).containsAll(primeImplicant.getResult()); + testPrimeImplicantProperty(formula, primeImplicant.getResult()); } } } @@ -158,11 +156,11 @@ public static void testPrimeImplicantProperty(final Formula formula, final Sorte final FormulaFactory f = formula.factory(); final SATSolver solver = SATSolver.newSolver(f); solver.add(formula.negate(f)); - Assertions.assertThat(solver.satCall().addFormulas(primeImplicant).sat()).isEqualTo(Tristate.FALSE); + assertThat(solver.satCall().addFormulas(primeImplicant).sat().getResult()).isFalse(); for (final Literal lit : primeImplicant) { final SortedSet reducedPrimeImplicant = new TreeSet<>(primeImplicant); reducedPrimeImplicant.remove(lit); - Assertions.assertThat(solver.satCall().addFormulas(reducedPrimeImplicant).sat()).isEqualTo(Tristate.TRUE); + assertThat(solver.satCall().addFormulas(reducedPrimeImplicant).sat().getResult()).isTrue(); } } } diff --git a/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicateReductionTest.java b/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicateReductionTest.java index 9d876a5f..345c6fdf 100644 --- a/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicateReductionTest.java +++ b/src/test/java/com/booleworks/logicng/primecomputation/PrimeImplicateReductionTest.java @@ -7,7 +7,6 @@ import static org.assertj.core.api.Assertions.assertThat; import com.booleworks.logicng.RandomTag; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.FormulaFactory; @@ -15,6 +14,7 @@ import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.BoundedSatHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.FormulaReader; @@ -43,16 +43,15 @@ public class PrimeImplicateReductionTest extends TestWithFormulaContext { @MethodSource("contexts") public void testPrimeImplicateNaive(final FormulaContext _c) throws ParserException { final NaivePrimeReduction naive01 = new NaivePrimeReduction(_c.f, _c.f.parse("a&b")); - Assertions.assertThat(naive01.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.a, _c.b)))) + assertThat(naive01.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.a, _c.b)))) .containsAnyOf(_c.a, _c.b).hasSize(1); final NaivePrimeReduction naive02 = new NaivePrimeReduction(_c.f, _c.f.parse("(a => b) | b | c")); - Assertions - .assertThat(naive02.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.a.negate(_c.f), _c.b, _c.c)))) + assertThat(naive02.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.a.negate(_c.f), _c.b, _c.c)))) .containsExactly(_c.a.negate(_c.f), _c.b, _c.c); final NaivePrimeReduction naive03 = new NaivePrimeReduction(_c.f, _c.f.parse("(a => b) & b & c")); - Assertions.assertThat(naive03.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.b, _c.c)))) + assertThat(naive03.reduceImplicate(_c.f, new TreeSet<>(Arrays.asList(_c.b, _c.c)))) .containsAnyOf(_c.b, _c.c).hasSize(1); } @@ -127,20 +126,19 @@ private void testFormula(final Formula formula, final ComputationHandler handler final SATSolver solver = SATSolver.newSolver(f); solver.add(formula.negate(f)); try (final SATCall call = solver.satCall().solve()) { - final boolean isSAT = call.getSatResult() == Tristate.TRUE; - if (!isSAT) { + if (!call.getSatResult().getResult()) { return; } final SortedSet falsifyingAssignment = FormulaHelper.negateLiterals(f, call.model(formula.variables(f)).literals(), TreeSet::new); final NaivePrimeReduction naive = new NaivePrimeReduction(f, formula); - final SortedSet primeImplicate = naive.reduceImplicate(f, falsifyingAssignment, handler); + final LNGResult> primeImplicate = naive.reduceImplicate(f, falsifyingAssignment, handler); if (expAborted) { - assertThat(handler.isAborted()).isTrue(); - assertThat(primeImplicate).isNull(); + assertThat(primeImplicate.isSuccess()).isFalse(); + assertThat(primeImplicate.getResult()).isNull(); } else { - assertThat(falsifyingAssignment).containsAll(primeImplicate); - testPrimeImplicateProperty(formula, primeImplicate); + assertThat(falsifyingAssignment).containsAll(primeImplicate.getResult()); + testPrimeImplicateProperty(formula, primeImplicate.getResult()); } } } @@ -150,11 +148,11 @@ public static void testPrimeImplicateProperty(final Formula formula, final Sorte final SATSolver solver = SATSolver.newSolver(f); solver.add(formula); final SortedSet negatedLiterals = FormulaHelper.negateLiterals(f, primeImplicate, TreeSet::new); - Assertions.assertThat(solver.satCall().addFormulas(negatedLiterals).sat()).isEqualTo(Tristate.FALSE); + assertThat(solver.satCall().addFormulas(negatedLiterals).sat().getResult()).isFalse(); for (final Literal lit : negatedLiterals) { final SortedSet reducedNegatedLiterals = new TreeSet<>(negatedLiterals); reducedNegatedLiterals.remove(lit); - Assertions.assertThat(solver.satCall().addFormulas(reducedNegatedLiterals).sat()).isEqualTo(Tristate.TRUE); + assertThat(solver.satCall().addFormulas(reducedNegatedLiterals).sat().getResult()).isTrue(); } } } diff --git a/src/test/java/com/booleworks/logicng/primecomputation/PrimeResultTest.java b/src/test/java/com/booleworks/logicng/primecomputation/PrimeResultTest.java index c784f21f..9a80176a 100644 --- a/src/test/java/com/booleworks/logicng/primecomputation/PrimeResultTest.java +++ b/src/test/java/com/booleworks/logicng/primecomputation/PrimeResultTest.java @@ -10,7 +10,6 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.TestWithFormulaContext; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -51,19 +50,19 @@ public PrimeResultTest() { @Test public void testGetters() { assertThat(result1.getPrimeImplicants()).hasSize(2); - Assertions.assertThat(result1.getPrimeImplicants().get(0)).containsExactly(c.a, c.nb); - Assertions.assertThat(result1.getPrimeImplicants().get(1)).containsExactly(c.a, c.c); + assertThat(result1.getPrimeImplicants().get(0)).containsExactly(c.a, c.nb); + assertThat(result1.getPrimeImplicants().get(1)).containsExactly(c.a, c.c); assertThat(result2.getPrimeImplicants()).hasSize(2); - Assertions.assertThat(result2.getPrimeImplicants().get(0)).containsExactly(c.a, c.nb); - Assertions.assertThat(result2.getPrimeImplicants().get(1)).containsExactly(c.c); + assertThat(result2.getPrimeImplicants().get(0)).containsExactly(c.a, c.nb); + assertThat(result2.getPrimeImplicants().get(1)).containsExactly(c.c); assertThat(result3.getPrimeImplicants()).hasSize(1); - Assertions.assertThat(result3.getPrimeImplicants().get(0)).isEmpty(); + assertThat(result3.getPrimeImplicants().get(0)).isEmpty(); assertThat(result1.getPrimeImplicates()).hasSize(1); - Assertions.assertThat(result1.getPrimeImplicates().get(0)).containsExactly(c.a, c.nb); + assertThat(result1.getPrimeImplicates().get(0)).containsExactly(c.a, c.nb); assertThat(result2.getPrimeImplicates()).hasSize(0); assertThat(result3.getPrimeImplicates()).hasSize(1); - Assertions.assertThat(result3.getPrimeImplicates().get(0)).containsExactly(c.nb); + assertThat(result3.getPrimeImplicates().get(0)).containsExactly(c.nb); assertThat(result1.getCoverageType()).isEqualTo(PrimeResult.CoverageType.IMPLICANTS_COMPLETE); assertThat(result2.getCoverageType()).isEqualTo(PrimeResult.CoverageType.IMPLICANTS_COMPLETE); diff --git a/src/test/java/com/booleworks/logicng/propositions/ExtendedPropositionTest.java b/src/test/java/com/booleworks/logicng/propositions/ExtendedPropositionTest.java index 7905f35a..a01cc576 100644 --- a/src/test/java/com/booleworks/logicng/propositions/ExtendedPropositionTest.java +++ b/src/test/java/com/booleworks/logicng/propositions/ExtendedPropositionTest.java @@ -29,8 +29,8 @@ public ExtendedPropositionTest() throws ParserException { @Test public void testGetters() throws ParserException { - Assertions.assertThat(prop1.formula()).isEqualTo(p.parse("a & b")); - Assertions.assertThat(prop2.formula()).isEqualTo(p.parse("a & b & ~c")); + assertThat(prop1.formula()).isEqualTo(p.parse("a & b")); + assertThat(prop2.formula()).isEqualTo(p.parse("a & b & ~c")); assertThat(prop1.backpack().description).isEqualTo("prop1"); assertThat(prop2.backpack().description).isEqualTo("prop2"); diff --git a/src/test/java/com/booleworks/logicng/propositions/StandardPropositionTest.java b/src/test/java/com/booleworks/logicng/propositions/StandardPropositionTest.java index 74fe9fee..d8acd6a3 100644 --- a/src/test/java/com/booleworks/logicng/propositions/StandardPropositionTest.java +++ b/src/test/java/com/booleworks/logicng/propositions/StandardPropositionTest.java @@ -27,8 +27,8 @@ public StandardPropositionTest() throws ParserException { @Test public void testGetters() throws ParserException { - Assertions.assertThat(prop1.formula()).isEqualTo(p.parse("a & b")); - Assertions.assertThat(prop2.formula()).isEqualTo(p.parse("a & b & ~c")); + assertThat(prop1.formula()).isEqualTo(p.parse("a & b")); + assertThat(prop2.formula()).isEqualTo(p.parse("a & b & ~c")); assertThat(prop1.description()).isEqualTo(""); assertThat(prop2.description()).isEqualTo("prop2"); diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/BackboneFunctionTest.java b/src/test/java/com/booleworks/logicng/solvers/functions/BackboneFunctionTest.java index 6b593cf8..81d7846a 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/BackboneFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/BackboneFunctionTest.java @@ -58,7 +58,7 @@ public void testConstants(final SATSolver solver, final String solverDescription solver.add(f.verum()); backbone = solver.backbone(v("a b c", f)); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); } @ParameterizedTest(name = "{index} {1}") @@ -75,7 +75,7 @@ public void testSimpleBackbones(final SATSolver solver, final String solverDescr solver.add(f.parse("~a & ~b & c")); backbone = solver.backbone(v("a c", f)); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.literal("a", false), f.variable("c")); + assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.literal("a", false), f.variable("c")); } @ParameterizedTest(name = "{index} {1}") @@ -85,13 +85,13 @@ public void testSimpleFormulas(final SATSolver solver, final String solverDescri solver.add(f.parse("(a => c | d) & (b => d | ~e) & (a | b)")); Backbone backbone = solver.backbone(v("a b c d e f", f)); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); solver.add(f.parse("a => b")); solver.add(f.parse("b => a")); solver.add(f.parse("~d")); backbone = solver.backbone(v("a b c d e f g h", f)); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.variable("a"), f.variable("b"), + assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.variable("a"), f.variable("b"), f.variable("c"), f.literal("d", false), f.literal("e", false)); } @@ -106,13 +106,13 @@ public void testSimpleFormulasWithBuilderUsage(final SATSolver solver, final Str f.variable("a"), f.variable("b"), f.variable("c"), f.variable("d"), f.variable("e"), f.variable("f")) .build()); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); solver.add(f.parse("a => b")); solver.add(f.parse("b => a")); solver.add(f.parse("~d")); backbone = solver.backbone(v("a b c d e f g h", f)); assertThat(backbone.isSat()).isTrue(); - Assertions.assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.variable("a"), f.variable("b"), + assertThat(backbone.getCompleteBackbone(f)).containsExactly(f.variable("a"), f.variable("b"), f.variable("c"), f.literal("d", false), f.literal("e", false)); } @@ -134,30 +134,30 @@ public void testRealFormulaIncremental1(final SATSolver solver, final String sol } reader.close(); Backbone backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); solver.add(f.variable("v411")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v385")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v275")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v188")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v103")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v404")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); assertThat(backbone.isSat()).isFalse(); } @@ -178,30 +178,30 @@ public void testRealFormulaIncremental2(final SATSolver solver, final String sol } reader.close(); Backbone backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); solver.add(f.variable("v2609")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v2416")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v2048")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v39")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v1663")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); assertThat(backbone.isSat()).isTrue(); solver.add(f.variable("v2238")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); assertThat(backbone.isSat()).isFalse(); } @@ -223,40 +223,40 @@ public void testRealFormulaIncrementalDecremental1(final SATSolver solver, final } reader.close(); Backbone backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); solver.add(f.variable("v411")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v411 & v385")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v411 & v385 & v275")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v411 & v385 & v275 & v188")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v411 & v385 & v275 & v188 & v103")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v411 & v385 & v275 & v188 & v103 & v404")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); assertThat(backbone.isSat()).isFalse(); } @@ -278,40 +278,40 @@ public void testRealFormulaIncrementalDecremental2(final SATSolver solver, final } reader.close(); Backbone backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(0), f)); solver.add(f.variable("v2609")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(1), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v2609 & v2416")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(2), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v2609 & v2416 & v2048")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(3), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v2609 & v2416 & v2048 & v39")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(4), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v2609 & v2416 & v2048 & v39 & v1663")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); + assertThat(backbone.getCompleteBackbone(f)).isEqualTo(parseBackbone(expectedBackbones.get(5), f)); assertThat(backbone.isSat()).isTrue(); solver.loadState(state); solver.add(f.parse("v2609 & v2416 & v2048 & v39 & v1663 & v2238")); backbone = solver.backbone(formula.variables(f)); - Assertions.assertThat(backbone.getCompleteBackbone(f)).isEmpty(); + assertThat(backbone.getCompleteBackbone(f)).isEmpty(); assertThat(backbone.isSat()).isFalse(); } @@ -325,7 +325,7 @@ public void testMiniCardSpecialCase() throws ParserException { f.parse("(v1 => v1234) & (v2 => v1234) & (v3 => v1234) & (v4 => v1234) & (v5 => v50) & (v6 => v60)")); miniCard.add(f.parse("~v6")); final Backbone backboneMC = miniCard.backbone(Arrays.asList(f.variable("v6"), f.variable("v60"))); - Assertions.assertThat(backboneMC.getNegativeBackbone()).extracting(Variable::name) + assertThat(backboneMC.getNegativeBackbone()).extracting(Variable::name) .containsExactlyInAnyOrder("v6", "v60"); } diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/ModelCountingFunctionTest.java b/src/test/java/com/booleworks/logicng/solvers/functions/ModelCountingFunctionTest.java index ab002630..fd133434 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/ModelCountingFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/ModelCountingFunctionTest.java @@ -15,6 +15,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; import com.booleworks.logicng.handlers.NumberOfModelsHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.modelcounting.ModelCounter; @@ -64,7 +66,7 @@ public void testTautology(final SplitVariableProvider splitProvider) { ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final BigInteger numberOfModels = @@ -79,7 +81,7 @@ public void testEmptyEnumerationVariables(final SplitVariableProvider splitProvi ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A & (B | C)"); @@ -96,7 +98,7 @@ public void testSimple1(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & (B | C)")); @@ -112,7 +114,7 @@ public void testSimple2(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); @@ -128,7 +130,7 @@ public void testMultipleModelEnumeration(final SplitVariableProvider splitProvid ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -148,7 +150,7 @@ public void testDontCareVariables1(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -167,7 +169,7 @@ public void testDontCareVariables2(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -187,11 +189,11 @@ public void testDontCareVariables3() throws ParserException { .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()).build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A | B | (X & ~X)"); // X will be - // simplified out - // and become a - // don't care - // variable unknown - // by the solver + // simplified out + // and become a + // don't care + // variable unknown + // by the solver solver.add(formula); final SortedSet variables = new TreeSet<>(f.variables("A", "B", "X")); final BigInteger numberOfModels = solver.execute(ModelCountingFunction.builder(variables) @@ -205,17 +207,19 @@ public void testDontCareVariables3() throws ParserException { public void testHandlerWithNumModelsLimit(final SplitVariableProvider splitProvider) throws ParserException { final NumberOfModelsHandler handler = new NumberOfModelsHandler(3); final ModelEnumerationConfig config = - ModelEnumerationConfig.builder().handler(handler) + ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder() .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); solver.add(formula); - final BigInteger numberOfModels = - solver.execute(ModelCountingFunction.builder(formula.variables(f)).configuration(config).build()); - assertThat(handler.isAborted()).isTrue(); - assertThat(numberOfModels).isEqualTo(3); + final LNGResult numberOfModels = solver.execute( + ModelCountingFunction.builder(formula.variables(f)).configuration(config).build(), handler); + assertThat(numberOfModels.isSuccess()).isFalse(); + assertThat(numberOfModels).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial) numberOfModels).getPartialResult().get()) + .isEqualTo(3); } @Test @@ -235,7 +239,7 @@ public void testRandomFormulas() { // recursive call: least common vars final ModelEnumerationConfig configLcv = ModelEnumerationConfig.builder().strategy(DefaultModelEnumerationStrategy.builder() - .splitVariableProvider(new LeastCommonVariablesProvider()).maxNumberOfModels(500).build()) + .splitVariableProvider(new LeastCommonVariablesProvider()).maxNumberOfModels(500).build()) .build(); final BigInteger count1 = solver .execute(ModelCountingFunction.builder(formula.variables(f)).configuration(configLcv).build()); diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunctionTest.java b/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunctionTest.java index d7f287d8..2f87723d 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationFunctionTest.java @@ -16,7 +16,6 @@ import com.booleworks.logicng.collections.LNGBooleanVector; import com.booleworks.logicng.collections.LNGIntVector; import com.booleworks.logicng.datastructures.Model; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.FormulaFactory; @@ -24,6 +23,8 @@ import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; import com.booleworks.logicng.handlers.NumberOfModelsHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.modelcounting.ModelCounter; @@ -79,7 +80,7 @@ public void testContradiction(final SplitVariableProvider splitProvider) { ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.literal("A", true)); @@ -96,7 +97,7 @@ public void testTautology(final SplitVariableProvider splitProvider) { ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); List models = solver.execute(ModelEnumerationFunction.builder(List.of()).configuration(config).build()); @@ -115,7 +116,7 @@ public void testEmptyEnumerationVariables(final SplitVariableProvider splitProvi ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A & (B | C)"); @@ -135,7 +136,7 @@ public void testSimple1(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & (B | C)")); @@ -155,7 +156,7 @@ public void testSimple2(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); @@ -172,7 +173,7 @@ public void testResultLiteralOrderIndependentFromInputOrder(final SplitVariableP ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & (B | C)")); @@ -199,7 +200,7 @@ public void testDuplicateEnumerationVariables(final SplitVariableProvider splitP ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & (B | C)")); @@ -219,7 +220,7 @@ public void testMultipleModelEnumeration(final SplitVariableProvider splitProvid ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -239,7 +240,7 @@ public void testAdditionalVariablesSimple(final SplitVariableProvider splitProvi ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & C | B & ~C")); @@ -263,7 +264,7 @@ public void testDuplicateAdditionalVariables(final SplitVariableProvider splitPr ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & (B | C)")); @@ -282,7 +283,7 @@ public void testDontCareVariables1(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); @@ -312,7 +313,7 @@ public void testDontCareVariables2(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); @@ -347,11 +348,11 @@ public void testDontCareVariables3() throws ParserException { .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()).build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A | B | (X & ~X)"); // X will be - // simplified out - // and become a - // don't care - // variable unknown - // by the solver + // simplified out + // and become a + // don't care + // variable unknown + // by the solver solver.add(formula); final SortedSet enumerationVars = new TreeSet<>(f.variables("A", "B", "X")); final List models = solver.execute(ModelEnumerationFunction.builder(enumerationVars) @@ -365,16 +366,17 @@ public void testDontCareVariables3() throws ParserException { public void testHandlerWithNumModelsLimit(final SplitVariableProvider splitProvider) throws ParserException { final NumberOfModelsHandler handler = new NumberOfModelsHandler(3); final ModelEnumerationConfig config = - ModelEnumerationConfig.builder().handler(handler) + ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder() .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); - final List models = solver - .execute(ModelEnumerationFunction.builder(f.variables("A", "B", "C")).configuration(config).build()); - assertThat(handler.isAborted()).isTrue(); - assertThat(models).hasSize(3); + final LNGResult> models = solver.execute( + ModelEnumerationFunction.builder(f.variables("A", "B", "C")).configuration(config).build(), handler); + assertThat(models.isSuccess()).isFalse(); + assertThat(models).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial, List>) models).getPartialResult().get()).hasSize(3); } @RandomTag @@ -411,7 +413,7 @@ public void testAdditionalVariables() { // additional variables for (final Model model : modelsRecursive) { assertThat(variables(model)).containsAll(additionalVars); - assertThat(solver.satCall().addFormulas(model.getLiterals()).sat()).isEqualTo(Tristate.TRUE); + assertThat(solver.satCall().addFormulas(model.getLiterals()).sat().getResult()).isTrue(); } } } @@ -538,15 +540,15 @@ public void testGetCartesianProduct(final FormulaContext _c) { singletonList(_c.na)); assertThat(getCartesianProduct(new TreeSet<>( List.of(_c.a, _c.b, _c.c)))).containsExactly( - List.of(_c.a, _c.b, _c.c), - List.of(_c.a, _c.b, _c.nc), - List.of(_c.a, _c.nb, _c.c), - List.of(_c.a, _c.nb, _c.nc), - List.of(_c.na, _c.b, _c.c), - List.of(_c.na, _c.b, _c.nc), - List.of(_c.na, _c.nb, _c.c), - List.of(_c.na, _c.nb, _c.nc) - ); + List.of(_c.a, _c.b, _c.c), + List.of(_c.a, _c.b, _c.nc), + List.of(_c.a, _c.nb, _c.c), + List.of(_c.a, _c.nb, _c.nc), + List.of(_c.na, _c.b, _c.c), + List.of(_c.na, _c.b, _c.nc), + List.of(_c.na, _c.nb, _c.c), + List.of(_c.na, _c.nb, _c.nc) + ); } @Test @@ -571,8 +573,8 @@ public void testVariableRemovedBySimplificationOccursInModels() throws ParserExc final Variable b = f.variable("B"); final Formula formula = this.f.parse("A & B => A"); solver.add(formula); // during NNF conversion, used by the PG - // transformation, the formula simplifies to verum - // when added to the solver + // transformation, the formula simplifies to verum + // when added to the solver final List models = solver.enumerateAllModels(formula.variables(f)); assertThat(models).hasSize(4); for (final Model model : models) { diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunctionTest.java b/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunctionTest.java index f92d3082..0ee7406a 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/ModelEnumerationToBddFunctionTest.java @@ -16,6 +16,8 @@ import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.formulas.Variable; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; import com.booleworks.logicng.handlers.NumberOfModelsHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.knowledgecompilation.bdds.BDD; @@ -65,7 +67,7 @@ public void testContradiction(final SplitVariableProvider splitProvider) { ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.literal("A", true)); @@ -81,7 +83,7 @@ public void testTautology(final SplitVariableProvider splitProvider) { ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final BDD bdd = solver.execute(ModelEnumerationToBddFunction.builder(List.of()).configuration(config).build()); @@ -95,7 +97,7 @@ public void testEmptyEnumerationVariables(final SplitVariableProvider splitProvi ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A & (B | C)"); @@ -111,7 +113,7 @@ public void testSimple1(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("A & (B | C)"); @@ -128,7 +130,7 @@ public void testSimple2(final SplitVariableProvider splitProvider) throws Parser ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -146,7 +148,7 @@ public void testMultipleModelEnumeration(final SplitVariableProvider splitProvid ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -168,7 +170,7 @@ public void testDontCareVariables1(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -188,7 +190,7 @@ public void testDontCareVariables2(final SplitVariableProvider splitProvider) th ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder().splitVariableProvider(splitProvider) - .maxNumberOfModels(2).build()) + .maxNumberOfModels(2).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); final Formula formula = f.parse("(~A | C) & (~B | C)"); @@ -208,12 +210,9 @@ public void testDontCareVariables3() throws ParserException { ModelEnumerationConfig.builder().strategy(DefaultModelEnumerationStrategy.builder() .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()).build(); final SATSolver solver = SATSolver.newSolver(f); - final Formula formula = f.parse("A | B | (X & ~X)"); // X will be - // simplified out - // and become a - // don't care - // variable unknown - // by the solver + // X will be simplified out and become a don't care variable unknown + // by the solver + final Formula formula = f.parse("A | B | (X & ~X)"); solver.add(formula); final SortedSet variables = new TreeSet<>(f.variables("A", "B", "X")); final BDD bdd = solver.execute(ModelEnumerationToBddFunction.builder(variables) @@ -228,16 +227,18 @@ public void testDontCareVariables3() throws ParserException { public void testHandlerWithNumModelsLimit(final SplitVariableProvider splitProvider) throws ParserException { final NumberOfModelsHandler handler = new NumberOfModelsHandler(3); final ModelEnumerationConfig config = - ModelEnumerationConfig.builder().handler(handler) + ModelEnumerationConfig.builder() .strategy(splitProvider == null ? null : DefaultModelEnumerationStrategy.builder() .splitVariableProvider(splitProvider).maxNumberOfModels(3).build()) .build(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("(~A | C) & (~B | C)")); - final BDD bdd = solver.execute( - ModelEnumerationToBddFunction.builder(f.variables("A", "B", "C")).configuration(config).build()); - assertThat(handler.isAborted()).isTrue(); - assertThat(bdd.modelCount()).isEqualTo(3); + final LNGResult bdd = solver.execute( + ModelEnumerationToBddFunction.builder(f.variables("A", "B", "C")).configuration(config).build(), + handler); + assertThat(bdd.isSuccess()).isFalse(); + assertThat(bdd).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial) bdd).getPartialResult().get().modelCount()).isEqualTo(3); } @RandomTag @@ -254,7 +255,7 @@ public void testRandomFormulas() { // recursive call: least common vars final ModelEnumerationConfig configLcv = ModelEnumerationConfig.builder().strategy(DefaultModelEnumerationStrategy.builder() - .splitVariableProvider(new LeastCommonVariablesProvider()).maxNumberOfModels(500).build()) + .splitVariableProvider(new LeastCommonVariablesProvider()).maxNumberOfModels(500).build()) .build(); final BDD bdd1 = solver.execute( ModelEnumerationToBddFunction.builder(formula.variables(f)).configuration(configLcv).build()); @@ -262,7 +263,7 @@ public void testRandomFormulas() { // recursive call: most common vars final ModelEnumerationConfig configMcv = ModelEnumerationConfig.builder().strategy(DefaultModelEnumerationStrategy.builder() - .splitVariableProvider(new MostCommonVariablesProvider()).maxNumberOfModels(500).build()) + .splitVariableProvider(new MostCommonVariablesProvider()).maxNumberOfModels(500).build()) .build(); final BDD bdd2 = solver.execute( ModelEnumerationToBddFunction.builder(formula.variables(f)).configuration(configMcv).build()); diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/OptimizationFunctionTest.java b/src/test/java/com/booleworks/logicng/solvers/functions/OptimizationFunctionTest.java index 4ad2312b..6021c80e 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/OptimizationFunctionTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/OptimizationFunctionTest.java @@ -4,6 +4,7 @@ package com.booleworks.logicng.solvers.functions; +import static com.booleworks.logicng.solvers.functions.OptimizationFunction.builder; import static com.booleworks.logicng.solvers.sat.SolverTestSet.SATSolverConfigParam.CNF_METHOD; import static com.booleworks.logicng.solvers.sat.SolverTestSet.SATSolverConfigParam.INITIAL_PHASE; import static com.booleworks.logicng.solvers.sat.SolverTestSet.SATSolverConfigParam.PROOF_GENERATION; @@ -23,9 +24,12 @@ import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.handlers.BoundedOptimizationHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; import com.booleworks.logicng.handlers.NopHandler; +import com.booleworks.logicng.handlers.SatResult; import com.booleworks.logicng.handlers.TimeoutHandler; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.OptimizationFoundBetterBoundEvent; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.parsers.PropositionalParser; @@ -39,7 +43,6 @@ import com.booleworks.logicng.util.FormulaCornerCases; import com.booleworks.logicng.util.FormulaRandomizer; import com.booleworks.logicng.util.FormulaRandomizerConfig; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -79,12 +82,14 @@ public void testUnsatFormula(final Supplier solver, final FormulaFact final String solverDescription) throws ParserException { final Formula formula = f.parse("a & b & (a => ~b)"); - final Assignment minimumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), false, solver.get(), NopHandler.get()); - assertThat(minimumModel).isNull(); - final Assignment maximumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), true, solver.get(), NopHandler.get()); - assertThat(maximumModel).isNull(); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), false, solver.get(), NopHandler.get()); + assertThat(minimumModel.isSuccess()).isTrue(); + assertThat(minimumModel.getResult().isSat()).isFalse(); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), true, solver.get(), NopHandler.get()); + assertThat(maximumModel.isSuccess()).isTrue(); + assertThat(maximumModel.getResult().isSat()).isFalse(); } @ParameterizedTest(name = "{index} {2}") @@ -93,24 +98,25 @@ public void testSingleModel(final Supplier solver, final FormulaFacto final String solverDescription) throws ParserException { final Formula formula = f.parse("~a & ~b & ~c"); - final Assignment minimumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), false, solver.get(), NopHandler.get()); testMinimumModel(formula, minimumModel, formula.variables(f)); - final Assignment maximumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), true, solver.get(), NopHandler.get()); testMaximumModel(formula, maximumModel, formula.variables(f)); } @ParameterizedTest(name = "{index} {2}") @MethodSource("solverSuppliers") - public void testExoModel(final Supplier solver, final FormulaFactory f, final String solverDescription) { + public void testExoModel(final Supplier solver, final FormulaFactory f, + final String solverDescription) { final CardinalityConstraint exo = (CardinalityConstraint) f.exo(f.variable("a"), f.variable("b"), f.variable("c")); - final Assignment minimumModel = optimize(Collections.singleton(exo), exo.variables(f), Collections.emptyList(), - false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(exo), exo.variables(f), + Collections.emptyList(), false, solver.get(), NopHandler.get()); testMinimumModel(exo, minimumModel, exo.variables(f)); - final Assignment maximumModel = optimize(Collections.singleton(exo), exo.variables(f), Collections.emptyList(), - true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(exo), exo.variables(f), + Collections.emptyList(), true, solver.get(), NopHandler.get()); testMaximumModel(exo, maximumModel, exo.variables(f)); } @@ -121,13 +127,11 @@ public void testCornerCases(final Supplier solver, final FormulaFacto final FormulaCornerCases cornerCases = new FormulaCornerCases(f); for (final Formula formula : cornerCases.cornerCases()) { final Set targetLiterals = cornerCases.getVariables(); - - final Assignment minimumModel = optimize(Collections.singleton(formula), targetLiterals, - Collections.emptySet(), false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), + targetLiterals, Collections.emptySet(), false, solver.get(), NopHandler.get()); testMinimumModel(formula, minimumModel, targetLiterals); - - final Assignment maximumModel = optimize(Collections.singleton(formula), targetLiterals, - Collections.emptySet(), true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + targetLiterals, Collections.emptySet(), true, solver.get(), NopHandler.get()); testMaximumModel(formula, maximumModel, targetLiterals); } } @@ -151,12 +155,12 @@ public void testRandomSmall(final Supplier solver, final FormulaFacto randomTargetLiterals(f, random, randomSubset(random, variables, Math.min(variables.size(), 5))); final Set additionalVariables = randomSubset(random, variables, Math.min(variables.size(), 3)); - final Assignment minimumModel = optimize(Collections.singleton(formula), targetLiterals, - additionalVariables, false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), + targetLiterals, additionalVariables, false, solver.get(), NopHandler.get()); testMinimumModel(formula, minimumModel, targetLiterals); - final Assignment maximumModel = optimize(Collections.singleton(formula), targetLiterals, - additionalVariables, true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + targetLiterals, additionalVariables, true, solver.get(), NopHandler.get()); testMaximumModel(formula, maximumModel, targetLiterals); } } @@ -187,47 +191,45 @@ public void testIncrementalityMinimizeAndMaximize(final Supplier solv final SortedSet vars = new TreeSet<>(formula.variables(f)); solver.add(formula); - Assignment minimumModel = solver.execute(OptimizationFunction.builder().minimize().literals(vars).build()); - Assignment maximumModel = solver.execute(OptimizationFunction.builder().maximize().literals(vars).build()); - Assertions.assertThat(minimumModel.positiveVariables()).hasSize(3); - Assertions.assertThat(maximumModel.positiveVariables()).hasSize(10); + Assignment minimumModel = solver.execute(builder().minimize().literals(vars).build()).getResult(); + Assignment maximumModel = solver.execute(builder().maximize().literals(vars).build()).getResult(); + assertThat(minimumModel.positiveVariables()).hasSize(3); + assertThat(maximumModel.positiveVariables()).hasSize(10); formula = f.parse("~p"); vars.addAll(formula.variables(f)); solver.add(formula); - minimumModel = solver.execute(OptimizationFunction.builder().minimize().literals(vars).build()); - maximumModel = solver.execute(OptimizationFunction.builder().maximize().literals(vars).build()); - Assertions.assertThat(minimumModel.positiveVariables()).hasSize(3).contains(f.variable("q")); - Assertions.assertThat(maximumModel.positiveVariables()).hasSize(9).contains(f.variable("q")); + minimumModel = solver.execute(builder().minimize().literals(vars).build()).getResult(); + maximumModel = solver.execute(builder().maximize().literals(vars).build()).getResult(); + assertThat(minimumModel.positiveVariables()).hasSize(3).contains(f.variable("q")); + assertThat(maximumModel.positiveVariables()).hasSize(9).contains(f.variable("q")); formula = f.parse("(x => n) & (y => m) & (a => ~b & ~c)"); vars.addAll(formula.variables(f)); solver.add(formula); - minimumModel = solver.execute(OptimizationFunction.builder().minimize().literals(vars).build()); - maximumModel = solver.execute(OptimizationFunction.builder().maximize().literals(vars).build()); - Assertions.assertThat(minimumModel.positiveVariables()).hasSize(3).contains(f.variable("q"), f.variable("z")); - Assertions.assertThat(maximumModel.positiveVariables()).hasSize(10) + minimumModel = solver.execute(builder().minimize().literals(vars).build()).getResult(); + maximumModel = solver.execute(builder().maximize().literals(vars).build()).getResult(); + assertThat(minimumModel.positiveVariables()).hasSize(3).contains(f.variable("q"), f.variable("z")); + assertThat(maximumModel.positiveVariables()).hasSize(10) .contains(f.variable("q"), f.variable("z")) .doesNotContain(f.variable("a")); formula = f.parse("(z => v & w) & (m => v) & (b => ~c & ~d & ~e)"); vars.addAll(formula.variables(f)); solver.add(formula); - minimumModel = solver.execute(OptimizationFunction.builder().minimize().literals(vars).build()); - maximumModel = solver.execute(OptimizationFunction.builder().maximize().literals(vars).build()); - Assertions.assertThat(minimumModel.positiveVariables()).hasSize(4).contains(f.variable("q"), f.variable("x"), + minimumModel = solver.execute(builder().minimize().literals(vars).build()).getResult(); + maximumModel = solver.execute(builder().maximize().literals(vars).build()).getResult(); + assertThat(minimumModel.positiveVariables()).hasSize(4).contains(f.variable("q"), f.variable("x"), f.variable("n")); - Assertions.assertThat(maximumModel.positiveVariables()).hasSize(11) + assertThat(maximumModel.positiveVariables()).hasSize(11) .contains(f.variable("q"), f.variable("x"), f.variable("n"), f.variable("v"), f.variable("w")) .doesNotContain(f.variable("b")); formula = f.parse("~q"); vars.addAll(formula.variables(f)); solver.add(formula); - minimumModel = solver.execute(OptimizationFunction.builder().minimize().literals(vars).build()); - maximumModel = solver.execute(OptimizationFunction.builder().maximize().literals(vars).build()); - assertThat(minimumModel).isNull(); - assertThat(maximumModel).isNull(); + assertThat(solver.execute(builder().minimize().literals(vars).build()).isSat()).isFalse(); + assertThat(solver.execute(builder().maximize().literals(vars).build()).isSat()).isFalse(); } @ParameterizedTest(name = "{index} {2}") @@ -247,26 +249,27 @@ public void testAdditionalVariables(final Supplier solver, final Form final Formula formula = f.parse("(a|b) & (~a => c) & (x|y)"); final List literalsANBX = Arrays.asList(a, nb, x); - final Assignment minimumModel = optimize(Collections.singleton(formula), literalsANBX, Collections.emptyList(), - false, solver.get(), NopHandler.get()); - Assertions.assertThat(minimumModel.literals()).containsExactlyInAnyOrder(na, b, nx); - final Assignment minimumModelWithY = optimize(Collections.singleton(formula), literalsANBX, - Collections.singleton(y), false, solver.get(), NopHandler.get()); - Assertions.assertThat(minimumModelWithY.literals()).containsExactlyInAnyOrder(na, b, nx, y); - final Assignment minimumModelWithCY = - optimize(Collections.singleton(formula), literalsANBX, Arrays.asList(c, y), false, solver.get(), NopHandler.get()); - Assertions.assertThat(minimumModelWithCY.literals()).containsExactlyInAnyOrder(na, b, c, nx, y); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), literalsANBX, + Collections.emptyList(), false, solver.get(), NopHandler.get()); + assertThat(minimumModel.getResult().getResult().literals()).containsExactlyInAnyOrder(na, b, nx); + final LNGResult> minimumModelWithY = optimize(Collections.singleton(formula), + literalsANBX, Collections.singleton(y), false, solver.get(), NopHandler.get()); + assertThat(minimumModelWithY.getResult().getResult().literals()) + .containsExactlyInAnyOrder(na, b, nx, y); + final Assignment minimumModelWithCY = optimize(Collections.singleton(formula), + literalsANBX, Arrays.asList(c, y), false, solver.get(), NopHandler.get()).getResult().getResult(); + assertThat(minimumModelWithCY.literals()).containsExactlyInAnyOrder(na, b, c, nx, y); final List literalsNBNX = Arrays.asList(na, nx); final Assignment maximumModel = optimize(Collections.singleton(formula), literalsNBNX, Collections.emptyList(), - true, solver.get(), NopHandler.get()); - Assertions.assertThat(maximumModel.literals()).containsExactlyInAnyOrder(na, nx); + true, solver.get(), NopHandler.get()).getResult().getResult(); + assertThat(maximumModel.literals()).containsExactlyInAnyOrder(na, nx); final Assignment maximumModelWithC = optimize(Collections.singleton(formula), literalsNBNX, - Collections.singleton(c), true, solver.get(), NopHandler.get()); - Assertions.assertThat(maximumModelWithC.literals()).containsExactlyInAnyOrder(na, c, nx); + Collections.singleton(c), true, solver.get(), NopHandler.get()).getResult().getResult(); + assertThat(maximumModelWithC.literals()).containsExactlyInAnyOrder(na, c, nx); final Assignment maximumModelWithACY = optimize(Collections.singleton(formula), literalsNBNX, - Arrays.asList(a, c, y), true, solver.get(), NopHandler.get()); - Assertions.assertThat(maximumModelWithACY.literals()).containsExactlyInAnyOrder(na, c, nx, y); + Arrays.asList(a, c, y), true, solver.get(), NopHandler.get()).getResult().getResult(); + assertThat(maximumModelWithACY.literals()).containsExactlyInAnyOrder(na, c, nx, y); } @ParameterizedTest(name = "{index} {2}") @@ -278,8 +281,8 @@ public void testLargeFormulaMinimize(final Supplier solver, final For final Formula formula = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/large_formula.txt"); final List variables = randomSubset(formula.variables(f), 300); - final Assignment minimumModel = - optimize(Collections.singleton(formula), variables, Collections.emptyList(), false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), variables, + Collections.emptyList(), false, solver.get(), NopHandler.get()); testMinimumModel(formula, minimumModel, variables); } @@ -291,8 +294,8 @@ public void testLargeFormulaMaximize(final Supplier solver, final For throws IOException, ParserException { final Formula formula = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/large_formula.txt"); - final Assignment maximumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), true, solver.get(), NopHandler.get()); testMaximumModel(formula, maximumModel, formula.variables(f)); } @@ -304,8 +307,8 @@ public void testLargerFormulaMinimize(final Supplier solver, final Fo throws IOException, ParserException { final Formula formula = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/small_formulas.txt"); - final Assignment minimumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), false, solver.get(), NopHandler.get()); + final LNGResult> minimumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), false, solver.get(), NopHandler.get()); testMinimumModel(formula, minimumModel, formula.variables(f)); } @@ -318,8 +321,8 @@ public void testLargerFormulaMaximize(final Supplier solver, final Fo final Formula formula = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/small_formulas.txt"); final List variables = randomSubset(formula.variables(f), 300); - final Assignment maximumModel = - optimize(Collections.singleton(formula), variables, Collections.emptyList(), true, solver.get(), NopHandler.get()); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), variables, + Collections.emptyList(), true, solver.get(), NopHandler.get()); testMaximumModel(formula, maximumModel, variables); } @@ -342,14 +345,14 @@ public void compareWithMaxSat() throws IOException, ParserException { assertThat(solveMaxSat(formulas, variables, MaxSATSolver.linearUS(f))).isEqualTo(expected); assertThat(solveMaxSat(formulas, variables, MaxSATSolver.msu3(f))).isEqualTo(expected); assertThat(solveMaxSat(formulas, variables, MaxSATSolver.wbo(f))).isEqualTo(expected); - assertThat(satisfiedLiterals( - optimize(formulas, variables, Collections.emptyList(), false, - SATSolver.newSolver(f, SATSolverConfig.builder().useAtMostClauses(false).build()), NopHandler.get()), - variables).size()).isEqualTo(expected); - assertThat(satisfiedLiterals( - optimize(formulas, variables, Collections.emptyList(), false, - SATSolver.newSolver(f, SATSolverConfig.builder().useAtMostClauses(true).build()), NopHandler.get()), - variables).size()).isEqualTo(expected); + assertThat(satisfiedLiterals(optimize(formulas, variables, Collections.emptyList(), false, + SATSolver.newSolver(f, SATSolverConfig.builder().useAtMostClauses(false).build()), + NopHandler.get()), variables).size()) + .isEqualTo(expected); + assertThat(satisfiedLiterals(optimize(formulas, variables, Collections.emptyList(), false, + SATSolver.newSolver(f, SATSolverConfig.builder().useAtMostClauses(true).build()), + NopHandler.get()), variables).size()) + .isEqualTo(expected); } @ParameterizedTest(name = "{index} {2}") @@ -361,22 +364,28 @@ public void testTimeoutOptimizationHandler(final Supplier solver, fin final Formula formula = FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/large_formula.txt"); final TimeoutHandler handlerMax = new TimeoutHandler(1L); - final Assignment maximumModel = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), true, solver.get(), handlerMax); - assertThat(maximumModel).isNull(); - assertThat(handlerMax.isAborted()).isTrue(); + final LNGResult> maximumModel = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), true, solver.get(), handlerMax); + assertThat(maximumModel.isSuccess()).isFalse(); + assertThat(maximumModel).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial, SatResult>) maximumModel) + .getPartialResult()).isEmpty(); final TimeoutHandler handlerTooShort = new TimeoutHandler(0L); - final Assignment model = optimize(Collections.singleton(formula), formula.variables(f), Collections.emptyList(), - false, solver.get(), handlerTooShort); - assertThat(model).isNull(); - assertThat(handlerTooShort.isAborted()).isTrue(); + final LNGResult> model = optimize(Collections.singleton(formula), formula.variables(f), + Collections.emptyList(), false, solver.get(), handlerTooShort); + assertThat(model.isSuccess()).isFalse(); + assertThat(model).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial, SatResult>) model).getPartialResult()) + .isEmpty(); final CustomOptimizationHandler customHandler = new CustomOptimizationHandler(); - final Assignment modelCustom = optimize(Collections.singleton(formula), formula.variables(f), - Collections.emptyList(), true, solver.get(), customHandler); - assertThat(modelCustom).isNull(); - assertThat(customHandler.isAborted()).isTrue(); - assertThat(customHandler.currentResult).isNotNull(); + final LNGResult> modelCustom = optimize(Collections.singleton(formula), + formula.variables(f), Collections.emptyList(), true, solver.get(), customHandler); + assertThat(modelCustom.isSuccess()).isFalse(); + assertThat(modelCustom).isInstanceOf(LNGResultWithPartial.class); + assertThat(((LNGResultWithPartial, SatResult>) modelCustom) + .getPartialResult().get().getResult()).isNotNull(); + assertThat(modelCustom.getResult()).isNull(); } @ParameterizedTest(name = "{index} {2}") @@ -398,15 +407,10 @@ public void testCancellationPoints(final Supplier solverSupplier, fin for (int numSatHandlerStarts = 1; numSatHandlerStarts < 4; numSatHandlerStarts++) { solver.add(formulas); final ComputationHandler handler = new BoundedOptimizationHandler(numSatHandlerStarts, -1); - final OptimizationFunction optimizationFunction = OptimizationFunction.builder() - .handler(handler) - .literals(selVars) - .maximize().build(); - - final Assignment result = solver.execute(optimizationFunction); - - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isNull(); + final OptimizationFunction optimizationFunction = builder().literals(selVars).maximize().build(); + final LNGResult> result = solver.execute(optimizationFunction, handler); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getResult()).isNull(); } } @@ -418,54 +422,60 @@ private int solveMaxSat(final List formulas, final SortedSet return solver.result(); } - private SortedSet satisfiedLiterals(final Assignment assignment, + private SortedSet satisfiedLiterals(final LNGResult> assignment, final Collection literals) { - final SortedSet modelLiterals = assignment.literals(); + final SortedSet modelLiterals = assignment.getResult().getResult().literals(); return literals.stream().filter(modelLiterals::contains).collect(toCollection(TreeSet::new)); } - private static Assignment optimize(final Collection formulas, final Collection literals, - final Collection additionalVariables, final boolean maximize, - final SATSolver solver, final ComputationHandler handler) { + private static LNGResult> optimize( + final Collection formulas, final Collection literals, + final Collection additionalVariables, final boolean maximize, + final SATSolver solver, final ComputationHandler handler) { formulas.forEach(solver::add); if (maximize) { - return solver.execute(OptimizationFunction.builder().maximize().literals(literals) - .additionalVariables(additionalVariables).handler(handler).build()); + return solver.execute(builder().maximize().literals(literals) + .additionalVariables(additionalVariables).build(), handler); } else { - return solver.execute(OptimizationFunction.builder().minimize().literals(literals) - .additionalVariables(additionalVariables).handler(handler).build()); + return solver.execute(builder().minimize().literals(literals) + .additionalVariables(additionalVariables).build(), handler); } } - private void testMinimumModel(final Formula formula, final Assignment resultModel, + private void testMinimumModel(final Formula formula, final LNGResult> resultModel, final Collection literals) { testOptimumModel(formula, resultModel, literals, false); } - private void testMaximumModel(final Formula formula, final Assignment resultModel, + private void testMaximumModel(final Formula formula, final LNGResult> resultModel, final Collection literals) { testOptimumModel(formula, resultModel, literals, true); } - private void testOptimumModel(final Formula formula, final Assignment optimumModel, + private void testOptimumModel(final Formula formula, final LNGResult> optimumModel, final Collection literals, final boolean maximize) { + assertThat(optimumModel.isSuccess()).isTrue(); final FormulaFactory f = formula.factory(); final SATPredicate satPredicate = new SATPredicate(f); if (formula.holds(satPredicate)) { + assertThat(optimumModel.getResult().isSat()).isTrue(); + final SortedSet optimumLiterals = optimumModel.getResult().getResult().literals(); if (literals.isEmpty()) { - assertThat(optimumModel.literals()).isEmpty(); + assertThat(optimumLiterals).isEmpty(); } else { - assertThat(f.and(formula, f.and(optimumModel.literals())).holds(satPredicate)).isTrue(); + assertThat(f.and(formula, f.and(optimumLiterals)).holds(satPredicate)).isTrue(); final int actualNumSatisfied = satisfiedLiterals(optimumModel, literals).size(); final MaxSATSolver solver = MaxSATSolver.oll(f); solver.addHardFormula(formula); literals.forEach(l -> solver.addSoftFormula(maximize ? l : l.negate(f), 1)); solver.solve(); - final int numSatisfiedOll = satisfiedLiterals(solver.model(), literals).size(); + final int numSatisfiedOll = + satisfiedLiterals(LNGResult.of(SatResult.sat(solver.model())), literals).size(); assertThat(actualNumSatisfied).isEqualTo(numSatisfiedOll); } } else { - assertThat(optimumModel).isNull(); + assertThat(optimumModel.getResult().isSat()).isFalse(); + assertThat(optimumModel.getResult().getResult()).isNull(); } } @@ -480,12 +490,7 @@ private static class CustomOptimizationHandler implements ComputationHandler { private boolean aborted; @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event instanceof OptimizationFoundBetterBoundEvent) { currentResult = ((OptimizationFoundBetterBoundEvent) event).getModel().get(); aborted = currentResult.positiveVariables().size() >= 161; diff --git a/src/test/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollectorTestHandler.java b/src/test/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollectorTestHandler.java index c82b979d..8197eea2 100644 --- a/src/test/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollectorTestHandler.java +++ b/src/test/java/com/booleworks/logicng/solvers/functions/modelenumeration/EnumerationCollectorTestHandler.java @@ -6,8 +6,8 @@ import com.booleworks.logicng.handlers.ComputationHandler; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; import com.booleworks.logicng.handlers.events.EnumerationFoundModelsEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.SimpleEvent; public final class EnumerationCollectorTestHandler implements ComputationHandler { @@ -17,7 +17,7 @@ public final class EnumerationCollectorTestHandler implements ComputationHandler private int rollbackCalls; @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == ComputationStartedEvent.MODEL_ENUMERATION_STARTED) { foundModels = 0; } else if (event instanceof EnumerationFoundModelsEvent) { @@ -30,11 +30,6 @@ public boolean shouldResume(final LogicNGEvent event) { return true; } - @Override - public boolean isAborted() { - return false; - } - public int getFoundModels() { return foundModels; } diff --git a/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialMaxSATTest.java b/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialMaxSATTest.java index 8d517c46..0e4c16d9 100644 --- a/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialMaxSATTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialMaxSATTest.java @@ -12,9 +12,10 @@ import com.booleworks.logicng.TestWithExampleFormulas; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.handlers.events.ComputationStartedEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.MaxSatNewLowerBoundEvent; import com.booleworks.logicng.handlers.events.MaxSatNewUpperBoundEvent; import com.booleworks.logicng.io.parsers.ParserException; @@ -22,7 +23,6 @@ import com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT; import com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig; import com.booleworks.logicng.testutils.PigeonHoleGenerator; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.FileNotFoundException; @@ -80,7 +80,7 @@ public void testWBO() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.wbo(f, config); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -91,7 +91,7 @@ public void testOLL() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -105,7 +105,7 @@ public void testIncWBO() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.incWBO(f, config); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -126,7 +126,7 @@ public void testLinearSU() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.linearSU(f, config); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -149,7 +149,7 @@ public void testLinearUS() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.linearUS(f, config); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -171,7 +171,7 @@ public void testMSU3() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.msu3(f, config); readCnfToSolver(solver, "src/test/resources/partialmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -260,17 +260,16 @@ private void testTimeoutHandler(final MaxSATSolver solver) { final Formula formula = pg.generate(10); solver.addHardFormula(formula); solver.addSoftFormula(f.or(formula.variables(f)), 1); - MaxSAT.MaxSATResult result = solver.solve(handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.UNDEF); + LNGResult result = solver.solve(handler); + assertThat(result.isSuccess()).isFalse(); final TimeoutHandler handler2 = new TimeoutHandler(1000L); solver.reset(); solver.addHardFormula(IMP1); solver.addSoftFormula(AND1, 1); result = solver.solve(handler2); - assertThat(handler2.isAborted()).isFalse(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(result.isSuccess()).isTrue(); + assertThat(result.getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); } @Test @@ -279,9 +278,8 @@ public void testTimeoutHandlerSimple() throws IOException { MaxSATConfig.builder().verbosity(MaxSATConfig.Verbosity.SOME).output(logStream).build()); readCnfToSolver(solver, "src/test/resources/partialmaxsat/c1355_F176gat-1278gat@1.wcnf"); MaxSatTimeoutHandlerWithApproximation handler = new MaxSatTimeoutHandlerWithApproximation(1000L); - MaxSAT.MaxSATResult result = solver.solve(handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.UNDEF); + LNGResult result = solver.solve(handler); + assertThat(result.isSuccess()).isFalse(); assertThat(handler.lowerBoundApproximation).isLessThan(13); solver = MaxSATSolver.wbo(f, @@ -289,8 +287,8 @@ public void testTimeoutHandlerSimple() throws IOException { readCnfToSolver(solver, "src/test/resources/partialmaxsat/c1355_F1229gat@1.wcnf"); handler = new MaxSatTimeoutHandlerWithApproximation(5000L); result = solver.solve(handler); - assertThat(handler.isAborted()).isFalse(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(result.isSuccess()).isTrue(); + assertThat(result.getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); } @Test @@ -299,9 +297,9 @@ public void testTimeoutHandlerUB() throws IOException { MaxSATConfig.builder().verbosity(MaxSATConfig.Verbosity.SOME).output(logStream).build()); readCnfToSolver(solver, "src/test/resources/partialmaxsat/c1355_F1229gat@1.wcnf"); final MaxSatTimeoutHandlerWithApproximation handler = new MaxSatTimeoutHandlerWithApproximation(5000L); - final MaxSAT.MaxSATResult result = solver.solve(handler); - assertThat(handler.isAborted()).isFalse(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + final LNGResult result = solver.solve(handler); + assertThat(result.isSuccess()).isTrue(); + assertThat(result.getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); assertThat(solver.result()).isEqualTo(handler.upperBoundApproximation); } @@ -313,8 +311,8 @@ public void testNonClauselSoftConstraints() throws ParserException { for (final MaxSATSolver solver : solvers) { solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 1); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(1); @@ -330,8 +328,8 @@ public void testSoftConstraintsCornerCaseVerum() throws ParserException { solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("$true"), 1); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 1); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(1); @@ -347,8 +345,8 @@ public void testSoftConstraintsCornerCaseFalsum() throws ParserException { solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("$false"), 1); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 1); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(2); @@ -368,7 +366,7 @@ static class MaxSatTimeoutHandlerWithApproximation implements ComputationHandler } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event instanceof ComputationStartedEvent) { if (designatedEnd == 0) { designatedEnd = System.currentTimeMillis() + timeout; @@ -381,10 +379,5 @@ public boolean shouldResume(final LogicNGEvent event) { aborted = System.currentTimeMillis() >= designatedEnd; return !aborted; } - - @Override - public boolean isAborted() { - return aborted; - } } } diff --git a/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialWeightedMaxSATTest.java b/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialWeightedMaxSATTest.java index d4b16dcf..3b3f8a89 100644 --- a/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialWeightedMaxSATTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/maxsat/PartialWeightedMaxSATTest.java @@ -5,12 +5,14 @@ package com.booleworks.logicng.solvers.maxsat; import static com.booleworks.logicng.solvers.maxsat.MaxSATReader.readCnfToSolver; +import static com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT.MaxSATResult.OPTIMUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.booleworks.logicng.LongRunningTag; import com.booleworks.logicng.TestWithExampleFormulas; import com.booleworks.logicng.formulas.Formula; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.solvers.MaxSATSolver; @@ -87,7 +89,7 @@ public void testWBO() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.wbo(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -107,7 +109,7 @@ public void testIncWBO() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.incWBO(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -125,7 +127,7 @@ public void testLinearSU() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.linearSU(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -148,7 +150,7 @@ public void testWMSU3() throws IOException { for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.wmsu3(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -164,7 +166,7 @@ public void testWMSU3BMO() throws IOException { for (int i = 0; i < bmoFiles.length; i++) { final MaxSATSolver solver = MaxSATSolver.wmsu3(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/bmo/" + bmoFiles[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(bmoResults[i]); } } @@ -181,7 +183,7 @@ public void testLineaerSUBMO() throws IOException { for (int i = 0; i < bmoFiles.length; i++) { final MaxSATSolver solver = MaxSATSolver.linearSU(f, config); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/bmo/" + bmoFiles[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(bmoResults[i]); } } @@ -192,13 +194,13 @@ public void testOLL() throws IOException { for (int i = 0; i < bmoFiles.length; i++) { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/bmo/" + bmoFiles[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(bmoResults[i]); } for (int i = 0; i < files.length; i++) { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/" + files[i]); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(results[i]); } } @@ -208,7 +210,7 @@ public void testOLL() throws IOException { public void testLargeOLL1() throws IOException { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/large/large_industrial.wcnf"); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(68974); } @@ -217,7 +219,7 @@ public void testLargeOLL1() throws IOException { public void testLargeOLL2() throws IOException { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/large/t3g3-5555.spn.wcnf"); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1100610); } @@ -226,7 +228,7 @@ public void testLargeOLL2() throws IOException { public void testOLLWithLargeWeights() throws IOException { final MaxSATSolver solver = MaxSATSolver.oll(f); readCnfToSolver(solver, "src/test/resources/partialweightedmaxsat/large/large_weights.wcnf"); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(90912); } @@ -330,12 +332,12 @@ public void testWeightedNonClauseSoftConstraints() throws ParserException { for (final MaxSATSolver solver : solvers) { solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 2); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(2); - Assertions.assertThat(solver.factory()).isEqualTo(f); + assertThat(solver.factory()).isEqualTo(f); } } @@ -350,8 +352,8 @@ public void testWeightedSoftConstraintsCornerCaseVerum() throws ParserException solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("$true"), 2); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 3); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(3); @@ -369,8 +371,8 @@ public void testWeightedSoftConstraintsCornerCaseFalsum() throws ParserException solver.addHardFormula(f.parse("a & b & c")); solver.addSoftFormula(f.parse("$false"), 2); solver.addSoftFormula(f.parse("~a & ~b & ~c"), 3); - Assertions.assertThat(solver.solve()).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); - Assertions.assertThat(solver.model().literals()).containsExactlyInAnyOrder( + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); + assertThat(solver.model().literals()).containsExactlyInAnyOrder( f.variable("a"), f.variable("b"), f.variable("c") ); assertThat(solver.result()).isEqualTo(5); @@ -383,16 +385,15 @@ private void testTimeoutHandler(final MaxSATSolver solver) { final Formula formula = pg.generate(10); solver.addHardFormula(formula); solver.addSoftFormula(f.or(formula.variables(f)), 10); - MaxSAT.MaxSATResult result = solver.solve(handler); - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.UNDEF); + LNGResult result = solver.solve(handler); + assertThat(result.isSuccess()).isFalse(); final TimeoutHandler handler2 = new TimeoutHandler(1000L); solver.reset(); solver.addHardFormula(IMP1); solver.addSoftFormula(AND1, 10); result = solver.solve(handler2); - assertThat(handler2.isAborted()).isFalse(); - assertThat(result).isEqualTo(MaxSAT.MaxSATResult.OPTIMUM); + assertThat(result.isSuccess()).isTrue(); + assertThat(result.getResult()).isEqualTo(OPTIMUM); } } diff --git a/src/test/java/com/booleworks/logicng/solvers/maxsat/PureMaxSATTest.java b/src/test/java/com/booleworks/logicng/solvers/maxsat/PureMaxSATTest.java index dc03a4ff..3694d644 100644 --- a/src/test/java/com/booleworks/logicng/solvers/maxsat/PureMaxSATTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/maxsat/PureMaxSATTest.java @@ -19,7 +19,6 @@ import com.booleworks.logicng.solvers.MaxSATSolver; import com.booleworks.logicng.solvers.maxsat.algorithms.MaxSAT; import com.booleworks.logicng.solvers.maxsat.algorithms.MaxSATConfig; -import org.assertj.core.api.Assertions; import org.assertj.core.data.Offset; import org.junit.jupiter.api.Test; @@ -113,9 +112,9 @@ public void testCornerCase() throws ParserException { solver.addHardFormula(f.parse("a | b")); solver.addHardFormula(f.verum()); solver.addSoftFormula(A, 1); - MaxSAT.MaxSATResult result = solver.solve(); + MaxSAT.MaxSATResult result = solver.solve().getResult(); assertThat(result).isEqualTo(OPTIMUM); - result = solver.solve(); + result = solver.solve().getResult(); assertThat(result).isEqualTo(OPTIMUM); } @@ -131,12 +130,12 @@ public void testWBO() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } } @@ -153,12 +152,12 @@ public void testIncWBO() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.incWBO(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } } @@ -175,12 +174,12 @@ public void testLinearSU() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.linearSU(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } } @@ -205,12 +204,12 @@ public void testLinearUS() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.linearUS(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } } @@ -235,12 +234,12 @@ public void testMSU3() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.msu3(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.wbo(f, config); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } } @@ -251,12 +250,12 @@ public void testOLL() throws IOException { for (final String file : files) { final MaxSATSolver solver = MaxSATSolver.oll(f); MaxSATReader.readCnfToSolver(solver, "src/test/resources/maxsat/" + file); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(1); } final MaxSATSolver solver = MaxSATSolver.oll(f); MaxSATReader.readCnfToSolver(solver, "src/test/resources/sat/9symml_gr_rcs_w6.shuffled.cnf"); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(0); } @@ -265,7 +264,7 @@ public void testSingle() throws IOException { final MaxSATSolver solver = MaxSATSolver.incWBO(f, MaxSATConfig.builder() .cardinality(MaxSATConfig.CardinalityEncoding.MTOTALIZER).verbosity(SOME).output(logStream).build()); readCnfToSolver(solver, "src/test/resources/maxsat/c-fat200-2.clq.cnf"); - assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(26); final MaxSAT.Stats stats = solver.stats(); assertThat(stats.bestSolution()).isEqualTo(26); @@ -294,14 +293,14 @@ public void testAssignment() throws ParserException { solver.addSoftFormula(p.parse("a"), 1); solver.addSoftFormula(p.parse("~y"), 1); solver.addSoftFormula(p.parse("z"), 1); - Assertions.assertThat(solver.solve()).isEqualTo(OPTIMUM); + assertThat(solver.solve().getResult()).isEqualTo(OPTIMUM); assertThat(solver.result()).isEqualTo(3); final Assignment model = solver.model(); assertThat(model.size()).isEqualTo(8); - Assertions.assertThat(model.positiveVariables()).hasSize(1); - Assertions.assertThat(model.positiveVariables()).extracting(Variable::name).containsExactlyInAnyOrder("y"); - Assertions.assertThat(model.negativeLiterals()).hasSize(7); - Assertions.assertThat(model.negativeVariables()).extracting(Variable::name).containsExactlyInAnyOrder("a", "b", + assertThat(model.positiveVariables()).hasSize(1); + assertThat(model.positiveVariables()).extracting(Variable::name).containsExactlyInAnyOrder("y"); + assertThat(model.negativeLiterals()).hasSize(7); + assertThat(model.negativeVariables()).extracting(Variable::name).containsExactlyInAnyOrder("a", "b", "c", "d", "e", "x", "z"); } @@ -330,7 +329,8 @@ public void testToString() { solvers[4] = MaxSATSolver.wbo(f); solvers[5] = MaxSATSolver.wmsu3(f); - final String expected = "MaxSATSolver{result=OPTIMUM, var2index={@SEL_SOFT_0=2, @SEL_SOFT_1=3, a=0, b=1}}"; + final String expected = "MaxSATSolver{result=ComputationResult{result=OPTIMUM, abortionEvent=null}, " + + "var2index={@SEL_SOFT_0=2, @SEL_SOFT_1=3, a=0, b=1}}"; for (int i = 0; i < solvers.length; i++) { final MaxSATSolver solver = solvers[i]; diff --git a/src/test/java/com/booleworks/logicng/solvers/maxsat/encodings/EncodingsTest.java b/src/test/java/com/booleworks/logicng/solvers/maxsat/encodings/EncodingsTest.java index c74bd6dd..23861fe5 100644 --- a/src/test/java/com/booleworks/logicng/solvers/maxsat/encodings/EncodingsTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/maxsat/encodings/EncodingsTest.java @@ -20,7 +20,7 @@ public class EncodingsTest { @Test public void testTotalizer() { final Totalizer totalizer = new Totalizer(MaxSATConfig.IncrementalStrategy.ITERATIVE); - Assertions.assertThat(totalizer.incremental()).isEqualTo(MaxSATConfig.IncrementalStrategy.ITERATIVE); + assertThat(totalizer.incremental()).isEqualTo(MaxSATConfig.IncrementalStrategy.ITERATIVE); } @Test diff --git a/src/test/java/com/booleworks/logicng/solvers/sat/AssumeTest.java b/src/test/java/com/booleworks/logicng/solvers/sat/AssumeTest.java index e8615525..4fc5da8a 100644 --- a/src/test/java/com/booleworks/logicng/solvers/sat/AssumeTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/sat/AssumeTest.java @@ -9,13 +9,11 @@ import static org.assertj.core.api.Assertions.assertThat; import com.booleworks.logicng.LogicNGTest; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.parsers.PropositionalParser; import com.booleworks.logicng.solvers.SATSolver; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -52,26 +50,26 @@ public void testAssume() throws ParserException { s.add(parser.parse("c => d")); s.add(parser.parse("d => e")); s.add(parser.parse("e => f")); - assertThat(s.satCall().addFormulas(f.literal("a", false)).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("b")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("c")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("d")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("e")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("f")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("g")).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(f.variable("a")).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("b", false)).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("c", false)).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("d", false)).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("e", false)).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("f", false)).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(f.literal("g", false)).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(assumptions1).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(assumptions2).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(assumptions3).sat()).isEqualTo(Tristate.TRUE); - assertThat(s.satCall().addFormulas(assumptions4).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(assumptions5).sat()).isEqualTo(Tristate.FALSE); - assertThat(s.satCall().addFormulas(assumptions6).sat()).isEqualTo(Tristate.FALSE); + assertThat(s.satCall().addFormulas(f.literal("a", false)).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("b")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("c")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("d")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("e")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("f")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("g")).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(f.variable("a")).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("b", false)).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("c", false)).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("d", false)).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("e", false)).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("f", false)).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(f.literal("g", false)).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(assumptions1).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(assumptions2).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(assumptions3).sat().getResult()).isTrue(); + assertThat(s.satCall().addFormulas(assumptions4).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(assumptions5).sat().getResult()).isFalse(); + assertThat(s.satCall().addFormulas(assumptions6).sat().getResult()).isFalse(); } } } diff --git a/src/test/java/com/booleworks/logicng/solvers/sat/LNGCoreSolverTest.java b/src/test/java/com/booleworks/logicng/solvers/sat/LNGCoreSolverTest.java index 868e316f..ecf37ddf 100644 --- a/src/test/java/com/booleworks/logicng/solvers/sat/LNGCoreSolverTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/sat/LNGCoreSolverTest.java @@ -7,7 +7,6 @@ import static org.assertj.core.api.Assertions.assertThat; import com.booleworks.logicng.collections.LNGIntVector; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.handlers.NopHandler; import com.booleworks.logicng.io.parsers.ParserException; @@ -30,13 +29,13 @@ public void testAnalyzeAssumptionConflict() { solver.addClause(clause(-1, -2), null); solver.addClause(clause(-1, -3), null); solver.addClause(clause(-2, -3), null); - Assertions.assertThat(solver.internalSolve()).isEqualTo(Tristate.TRUE); - Assertions.assertThat(solver.internalSolve(NopHandler.get(), clause(1, 2))).isEqualTo(Tristate.FALSE); + assertThat(solver.internalSolve(NopHandler.get()).getResult()).isTrue(); + assertThat(solver.internalSolve(NopHandler.get(), clause(1, 2)).getResult()).isFalse(); } @Test public void testConfig() { - Assertions.assertThat(SATSolverConfig.builder().build().type().toString()).isEqualTo("SAT"); + assertThat(SATSolverConfig.builder().build().type().toString()).isEqualTo("SAT"); assertThat(Arrays.asList(SATSolverConfig.ClauseMinimization.values()) .contains(SATSolverConfig.ClauseMinimization.valueOf("DEEP"))).isTrue(); } @@ -46,15 +45,15 @@ public void testAssumptionChecking() throws ParserException { final FormulaFactory f = FormulaFactory.caching(); final SATSolver solver = SATSolver.newSolver(f); solver.add(f.parse("A & B")); - Assertions.assertThat(solver.sat()).isTrue(); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("A", true)).sat()).isEqualTo(Tristate.TRUE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("B", true)).sat()).isEqualTo(Tristate.TRUE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("A", false)).sat()).isEqualTo(Tristate.FALSE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("B", false)).sat()).isEqualTo(Tristate.FALSE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("A", true)).sat()).isEqualTo(Tristate.TRUE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("B", true)).sat()).isEqualTo(Tristate.TRUE); - Assertions.assertThat(solver.satCall().addFormulas(f.literal("A", false)).sat()).isEqualTo(Tristate.FALSE); - Assertions.assertThat(solver.sat()).isTrue(); + assertThat(solver.sat()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("A", true)).sat().getResult()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("B", true)).sat().getResult()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("A", false)).sat().getResult()).isFalse(); + assertThat(solver.satCall().addFormulas(f.literal("B", false)).sat().getResult()).isFalse(); + assertThat(solver.satCall().addFormulas(f.literal("A", true)).sat().getResult()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("B", true)).sat().getResult()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("A", false)).sat().getResult()).isFalse(); + assertThat(solver.sat()).isTrue(); } private LNGIntVector clause(final int... lits) { diff --git a/src/test/java/com/booleworks/logicng/solvers/sat/ModelTest.java b/src/test/java/com/booleworks/logicng/solvers/sat/ModelTest.java index 8a3e4236..79487eb1 100644 --- a/src/test/java/com/booleworks/logicng/solvers/sat/ModelTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/sat/ModelTest.java @@ -12,7 +12,6 @@ import com.booleworks.logicng.datastructures.Assignment; import com.booleworks.logicng.datastructures.Model; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; @@ -165,12 +164,12 @@ public void testNonCNFRestrictedVars(final Supplier solverSupplier, f final SortedSet relevantVariables = new TreeSet<>(Arrays.asList(f.variable("A"), f.variable("B"), f.variable("C"))); final Assignment model = solverForMe.satCall().model(relevantVariables); - assertThat(verificationSolver.satCall().addFormulas(model.literals()).sat()).isEqualTo(Tristate.TRUE); + assertThat(verificationSolver.satCall().addFormulas(model.literals()).sat().getResult()).isTrue(); assertThat(model.formula(f).variables(f)).isEqualTo(relevantVariables); final List allModels = solverForMe.enumerateAllModels(relevantVariables); assertThat(allModels).hasSize(2); for (final Model m : allModels) { - assertThat(verificationSolver.satCall().addFormulas(m.getLiterals()).sat()).isEqualTo(Tristate.TRUE); + assertThat(verificationSolver.satCall().addFormulas(m.getLiterals()).sat().getResult()).isTrue(); assertThat(m.formula(f).variables(f)).isEqualTo(relevantVariables); } } @@ -192,7 +191,7 @@ public void testNonCNFRestrictedAndAdditionalVars(final Supplier solv final SortedSet allVariables = new TreeSet<>(relevantVariables); allVariables.addAll(additionalVariables); final Assignment model = solverForMe.satCall().model(additionalVariables); - assertThat(verificationSolver.satCall().addFormulas(model.literals()).sat()).isEqualTo(Tristate.TRUE); + assertThat(verificationSolver.satCall().addFormulas(model.literals()).sat().getResult()).isTrue(); assertThat(model.formula(f).variables(f)).containsExactlyInAnyOrder(f.variable("D"), f.variable("X"), f.variable("Y")); final ModelEnumerationFunction me = ModelEnumerationFunction.builder(relevantVariables) @@ -202,7 +201,7 @@ public void testNonCNFRestrictedAndAdditionalVars(final Supplier solv final List allModels = solverForMe.execute(me); assertThat(allModels).hasSize(2); for (final Model m : allModels) { - assertThat(verificationSolver.satCall().addFormulas(m.getLiterals()).sat()).isEqualTo(Tristate.TRUE); + assertThat(verificationSolver.satCall().addFormulas(m.getLiterals()).sat().getResult()).isTrue(); assertThat(m.formula(f).variables(f)).isEqualTo(allVariables); } } diff --git a/src/test/java/com/booleworks/logicng/solvers/sat/SATCallTest.java b/src/test/java/com/booleworks/logicng/solvers/sat/SATCallTest.java index d1cd7816..293e1cfb 100644 --- a/src/test/java/com/booleworks/logicng/solvers/sat/SATCallTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/sat/SATCallTest.java @@ -4,13 +4,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.booleworks.logicng.datastructures.Assignment; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.formulas.implementation.cached.CachingFormulaFactory; import com.booleworks.logicng.handlers.ComputationHandler; import com.booleworks.logicng.handlers.TimeoutHandler; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.handlers.events.SimpleEvent; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.FormulaReader; @@ -70,8 +69,8 @@ public void testDirectSatMethod() throws ParserException { final SATSolver solver = SATSolver.newSolver(f, SATSolverConfig.builder().build()); solver.add(f.parse("a | b")); solver.add(f.parse("c & (~c | ~a)")); - assertThat(solver.satCall().sat()).isEqualTo(Tristate.TRUE); - assertThat(solver.satCall().addFormulas(f.literal("b", false)).sat()).isEqualTo(Tristate.FALSE); + assertThat(solver.satCall().sat().getResult()).isTrue(); + assertThat(solver.satCall().addFormulas(f.literal("b", false)).sat().getResult()).isFalse(); assertThat(solver.sat()).isTrue(); } @@ -134,19 +133,19 @@ public void testHandler() throws IOException, ParserException { solver.add(FormulaReader.readPropositionalFormula(f, "src/test/resources/formulas/small_formulas.txt")); try (final SATCall satCall = solver.satCall().handler(new MaxConflictsHandler(0)).solve()) { - assertThat(satCall.getSatResult()).isEqualTo(Tristate.UNDEF); + assertThat(satCall.getSatResult().isSuccess()).isFalse(); assertThat(satCall.model(solver.underlyingSolver().knownVariables())).isNull(); assertThat(satCall.unsatCore()).isNull(); } - assertThat(solver.satCall().handler(new MaxConflictsHandler(0)).sat()).isEqualTo(Tristate.UNDEF); + assertThat(solver.satCall().handler(new MaxConflictsHandler(0)).sat().isSuccess()).isFalse(); assertThat( solver.satCall().handler(new MaxConflictsHandler(0)).model(solver.underlyingSolver().knownVariables())) .isNull(); assertThat(solver.satCall().handler(new MaxConflictsHandler(0)).unsatCore()).isNull(); try (final SATCall satCall = solver.satCall().handler(new MaxConflictsHandler(100)).solve()) { - assertThat(satCall.getSatResult()).isEqualTo(Tristate.TRUE); + assertThat(satCall.getSatResult().getResult()).isTrue(); assertThat(satCall.model(solver.underlyingSolver().knownVariables())).isNotNull(); assertThat(satCall.unsatCore()).isNull(); } @@ -249,16 +248,11 @@ public MaxConflictsHandler(final int maxConflicts) { } @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == SimpleEvent.SAT_CONFLICT_DETECTED) { aborted = numConflicts++ > maxConflicts; } return !aborted; } - - @Override - public boolean isAborted() { - return aborted; - } } } diff --git a/src/test/java/com/booleworks/logicng/solvers/sat/SATTest.java b/src/test/java/com/booleworks/logicng/solvers/sat/SATTest.java index d74203c8..b88fa40c 100644 --- a/src/test/java/com/booleworks/logicng/solvers/sat/SATTest.java +++ b/src/test/java/com/booleworks/logicng/solvers/sat/SATTest.java @@ -20,15 +20,16 @@ import com.booleworks.logicng.TestWithExampleFormulas; import com.booleworks.logicng.datastructures.Assignment; import com.booleworks.logicng.datastructures.Model; -import com.booleworks.logicng.datastructures.Tristate; import com.booleworks.logicng.formulas.CType; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaFactory; import com.booleworks.logicng.formulas.FormulaFactoryConfig; import com.booleworks.logicng.formulas.Literal; import com.booleworks.logicng.formulas.Variable; -import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; +import com.booleworks.logicng.handlers.LNGResultWithPartial; import com.booleworks.logicng.handlers.NumberOfModelsHandler; +import com.booleworks.logicng.handlers.SatResult; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.parsers.PropositionalParser; @@ -385,9 +386,9 @@ public void testTimeoutSATHandlerSmall() { for (final SATSolver s : solvers) { s.add(IMP1); final TimeoutHandler handler = new TimeoutHandler(1000L); - final Tristate result = s.satCall().handler(handler).sat(); - assertThat(handler.isAborted()).isFalse(); - assertThat(result).isEqualTo(Tristate.TRUE); + final LNGResult result = s.satCall().handler(handler).sat(); + assertThat(result.isSuccess()).isTrue(); + assertThat(result.getResult()).isTrue(); } } @@ -397,9 +398,9 @@ public void testTimeoutSATHandlerLarge() { for (final SATSolver s : solvers) { s.add(pg.generate(10)); final TimeoutHandler handler = new TimeoutHandler(1000L); - final Tristate result = s.satCall().handler(handler).sat(); - assertThat(handler.isAborted()).isTrue(); - assertThat(result).isEqualTo(Tristate.UNDEF); + final LNGResult result = s.satCall().handler(handler).sat(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getResult()).isNull(); } } @@ -464,10 +465,9 @@ public void testTimeoutModelEnumerationHandlerWithUNSATInstance() { final Formula formula = pg.generate(10); solver.add(formula); final var handler = new TimeoutHandler(1000L); - final var me = meWithHandler(handler, formula.variables(f)); - final List assignments = solver.execute(me); - assertThat(assignments).isEmpty(); - assertThat(handler.isAborted()).isTrue(); + final var me = meWithHandler(formula.variables(f)); + final LNGResult> assignments = solver.execute(me, handler); + assertThat(assignments.isSuccess()).isFalse(); } } @@ -482,9 +482,9 @@ public void testTimeoutModelEnumerationHandlerWithSATInstance1() { solver.add(f.exo(variables)); final var handler = new TimeoutHandler(50L); - final var me = meWithHandler(handler, variables); - solver.execute(me); - assertThat(handler.isAborted()).isTrue(); + final var me = meWithHandler(variables); + final LNGResult> result = solver.execute(me, handler); + assertThat(result.isSuccess()).isFalse(); } } @@ -498,10 +498,10 @@ public void testTimeoutModelEnumerationHandlerWithSATInstance2() { solver.add(f.exo(variables.subList(0, 5))); final var handler = new TimeoutHandler(50L); - final var me = meWithHandler(handler, variables.subList(0, 5)); - final List assignments = solver.execute(me); - assertThat(assignments).hasSize(5); - assertThat(handler.isAborted()).isFalse(); + final var me = meWithHandler(variables.subList(0, 5)); + final LNGResult> assignments = solver.execute(me, handler); + assertThat(assignments.isSuccess()).isTrue(); + assertThat(assignments.getResult()).hasSize(5); } } @@ -551,13 +551,15 @@ public void testModelEnumerationWithHandler01() { final var handler = new NumberOfModelsHandler(29); final var me = ModelEnumerationFunction.builder(firstFive) .additionalVariables(lits) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - final List modelsWithHandler = s.execute(me); - assertThat(handler.isAborted()).isTrue(); - assertThat(modelsWithHandler.size()).isEqualTo(29); - for (final Model model : modelsWithHandler) { + final LNGResult> modelsWithHandler = s.execute(me, handler); + assertThat(modelsWithHandler.isSuccess()).isFalse(); + assertThat(modelsWithHandler).isInstanceOf(LNGResultWithPartial.class); + final List partialResult = ((LNGResultWithPartial, List>) modelsWithHandler) + .getPartialResult().get(); + assertThat(partialResult).hasSize(29); + for (final Model model : partialResult) { for (final Variable lit : lits) { assertThat(model.positiveVariables().contains(lit) || model.negativeVariables().contains(lit)) .isTrue(); @@ -583,13 +585,15 @@ public void testModelEnumerationWithHandler02() { final var handler = new NumberOfModelsHandler(29); final var me = ModelEnumerationFunction.builder(lits) .additionalVariables(firstFive) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - final List modelsWithHandler = s.execute(me); - assertThat(handler.isAborted()).isTrue(); - assertThat(modelsWithHandler.size()).isEqualTo(29); - for (final Model model : modelsWithHandler) { + final LNGResult> modelsWithHandler = s.execute(me, handler); + assertThat(modelsWithHandler.isSuccess()).isFalse(); + assertThat(modelsWithHandler).isInstanceOf(LNGResultWithPartial.class); + final List partialResult = ((LNGResultWithPartial, List>) modelsWithHandler) + .getPartialResult().get(); + assertThat(partialResult).hasSize(29); + for (final Model model : partialResult) { for (final Variable lit : lits) { assertThat(model.positiveVariables().contains(lit) || model.negativeVariables().contains(lit)) .isTrue(); @@ -619,14 +623,12 @@ public void testNumberOfModelHandler() { s.add(f.exo(lits)); var handler = new NumberOfModelsHandler(101); var me = ModelEnumerationFunction.builder(lits) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - - List models = s.execute(me); - assertThat(handler.isAborted()).isFalse(); - assertThat(models.size()).isEqualTo(100); - for (final Model m : models) { + LNGResult> models = s.execute(me, handler); + assertThat(models.isSuccess()).isTrue(); + assertThat(models.getResult().size()).isEqualTo(100); + for (final Model m : models.getResult()) { assertThat(m.positiveVariables().size()).isEqualTo(1); } @@ -634,13 +636,12 @@ public void testNumberOfModelHandler() { s.add(f.exo(lits)); handler = new NumberOfModelsHandler(200); me = ModelEnumerationFunction.builder(lits) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - models = s.execute(me); - assertThat(handler.isAborted()).isFalse(); - assertThat(models.size()).isEqualTo(100); - for (final Model m : models) { + models = s.execute(me, handler); + assertThat(models.isSuccess()).isTrue(); + assertThat(models.getResult().size()).isEqualTo(100); + for (final Model m : models.getResult()) { assertThat(m.positiveVariables().size()).isEqualTo(1); } @@ -648,13 +649,14 @@ public void testNumberOfModelHandler() { s.add(f.exo(lits)); handler = new NumberOfModelsHandler(50); me = ModelEnumerationFunction.builder(lits) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - models = s.execute(me); - assertThat(handler.isAborted()).isTrue(); - assertThat(models.size()).isEqualTo(50); - for (final Model m : models) { + models = s.execute(me, handler); + assertThat(models.isSuccess()).isFalse(); + assertThat(models).isInstanceOf(LNGResultWithPartial.class); + List partial = ((LNGResultWithPartial, List>) models).getPartialResult().get(); + assertThat(partial).hasSize(50); + for (final Model m : partial) { assertThat(m.positiveVariables().size()).isEqualTo(1); } @@ -662,13 +664,14 @@ public void testNumberOfModelHandler() { s.add(f.exo(lits)); handler = new NumberOfModelsHandler(1); me = ModelEnumerationFunction.builder(lits) - .configuration( - ModelEnumerationConfig.builder().strategy(defaultMeStrategy).handler(handler).build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); - models = s.execute(me); - assertThat(handler.isAborted()).isTrue(); - assertThat(models.size()).isEqualTo(1); - for (final Model m : models) { + models = s.execute(me, handler); + assertThat(models.isSuccess()).isFalse(); + assertThat(models).isInstanceOf(LNGResultWithPartial.class); + partial = ((LNGResultWithPartial, List>) models).getPartialResult().get(); + assertThat(partial).hasSize(1); + for (final Model m : partial) { assertThat(m.positiveVariables().size()).isEqualTo(1); } } @@ -719,8 +722,8 @@ public void testUPZeroLiteralsUNSAT() throws ParserException { final Formula formula = parser.parse("a & (a => b) & (b => c) & (c => ~a)"); for (final SATSolver solver : solvers) { solver.add(formula); - final SortedSet upLiterals = solver.execute(UpZeroLiteralsFunction.get()); - assertThat(upLiterals).isNull(); + final SatResult> upLiterals = solver.execute(UpZeroLiteralsFunction.get()); + assertThat(upLiterals.isSat()).isFalse(); } } @@ -746,7 +749,7 @@ public void testUPZeroLiterals() throws ParserException { solver.add(formula); final boolean res = solver.sat(); assertThat(res).isTrue(); - final SortedSet upLiterals = solver.execute(UpZeroLiteralsFunction.get()); + final SortedSet upLiterals = solver.execute(UpZeroLiteralsFunction.get()).getResult(); assertThat(upLiterals).containsAll(expectedSubsets.get(formula)); } } @@ -765,7 +768,7 @@ public void testUPZeroLiteralsDimacsFiles() throws IOException { final SATSolver solver = solverSupplier.get(); readCNF(solver, file); if (solver.sat()) { - final SortedSet upZeroLiterals = solver.execute(UpZeroLiteralsFunction.get()); + final SortedSet upZeroLiterals = solver.execute(UpZeroLiteralsFunction.get()).getResult(); final List negations = new ArrayList<>(upZeroLiterals.size()); for (final Literal lit : upZeroLiterals) { negations.add(lit.negate(f)); @@ -886,7 +889,7 @@ public void testSelectionOrderSimple02() { solver.add(f.cc(CType.EQ, 2, literals)); for (int i = 0; i < 10; ++i) { - assertThat(solver.satCall().selectionOrder(literals).sat()).isEqualTo(Tristate.TRUE); + assertThat(solver.satCall().selectionOrder(literals).sat().getResult()).isTrue(); final Assignment assignment = solver.satCall().selectionOrder(literals).model(literals); testLocalMinimum(solver, assignment, literals); testHighestLexicographicalAssignment(solver, assignment, literals); @@ -910,7 +913,7 @@ public void testSelectionOrderSimple03() { f.literal("x3", true)); for (int i = 0; i < 10; ++i) { - assertThat(solver.satCall().selectionOrder(selectionOrder02).sat()).isEqualTo(Tristate.TRUE); + assertThat(solver.satCall().selectionOrder(selectionOrder02).sat().getResult()).isTrue(); final Assignment assignment = solver.satCall().selectionOrder(selectionOrder02).model(literals); testLocalMinimum(solver, assignment, selectionOrder02); testHighestLexicographicalAssignment(solver, assignment, selectionOrder02); @@ -943,7 +946,7 @@ public void testDimacsFilesWithSelectionOrder() throws IOException { selectionOrder.add(var.negate(f)); } } - final boolean res = solver.satCall().selectionOrder(selectionOrder).sat() == Tristate.TRUE; + final boolean res = solver.satCall().selectionOrder(selectionOrder).sat().getResult(); assertThat(res).isEqualTo(expectedResults.get(fileName)); if (expectedResults.get(fileName)) { final Assignment assignment = @@ -1003,7 +1006,7 @@ private void testLocalMinimum(final SATSolver solver, final Assignment assignmen final SortedSet literalsWithFlip = new TreeSet<>(literals); literalsWithFlip.remove(lit.negate(f)); literalsWithFlip.add(lit); - assertThat(solver.satCall().addFormulas(literalsWithFlip).sat()).isEqualTo(Tristate.FALSE); + assertThat(solver.satCall().addFormulas(literalsWithFlip).sat().getResult()).isFalse(); } } } @@ -1025,19 +1028,15 @@ private void testHighestLexicographicalAssignment(final SATSolver solver, final final SortedSet orderSubsetWithFlip = new TreeSet<>(orderSublist); orderSubsetWithFlip.remove(lit.negate(f)); orderSubsetWithFlip.add(lit); - assertThat(solver.satCall().addFormulas(orderSubsetWithFlip).sat()).isEqualTo(Tristate.FALSE); + assertThat(solver.satCall().addFormulas(orderSubsetWithFlip).sat().getResult()).isFalse(); } orderSublist.add(containsLit ? lit : lit.negate(f)); } } - static ModelEnumerationFunction meWithHandler(final ComputationHandler handler, - final Collection variables) { + static ModelEnumerationFunction meWithHandler(final Collection variables) { return ModelEnumerationFunction.builder(variables) - .configuration(ModelEnumerationConfig.builder() - .strategy(defaultMeStrategy) - .handler(handler) - .build()) + .configuration(ModelEnumerationConfig.builder().strategy(defaultMeStrategy).build()) .build(); } diff --git a/src/test/java/com/booleworks/logicng/transformations/AIGTest.java b/src/test/java/com/booleworks/logicng/transformations/AIGTest.java index 5105e5fe..813170f8 100644 --- a/src/test/java/com/booleworks/logicng/transformations/AIGTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/AIGTest.java @@ -11,7 +11,6 @@ import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.predicates.AIGPredicate; -import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -79,24 +78,24 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { assertThat(_c.and1.transform(aigCaching)).isEqualTo(_c.and1); assertThat(_c.or1.transform(aigCaching)).isEqualTo(_c.p.parse("~(~x & ~y)")); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(aigCaching)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(aigCaching)) .isEqualTo(_c.p.parse("(~a & ~b) & c & ~(x & ~y) & ~(w & ~z)")); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(aigCaching)) + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(aigCaching)) .isEqualTo(_c.p.parse("~(a & b & ~c & ~(~x & y))")); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(aigCaching)) + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(aigCaching)) .isEqualTo(_c.p.parse("~(~a & ~b & ~(~x & ~y))")); assertThat(_c.and1.transform(aigCaching).holds(aigPred)).isTrue(); assertThat(_c.or1.transform(aigCaching).holds(aigPred)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(aigCaching).holds(aigPred)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(aigCaching).holds(aigPred)) .isTrue(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(aigCaching).holds(aigPred)).isTrue(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(aigCaching).holds(aigPred)).isTrue(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(aigCaching).holds(aigPred)).isTrue(); + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(aigCaching).holds(aigPred)).isTrue(); assertThat(_c.and1.holds(aigPred)).isTrue(); assertThat(_c.f.and(_c.and1, _c.pbc1).holds(aigPred)).isFalse(); assertThat(_c.or1.holds(aigPred)).isFalse(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").holds(aigPred)).isFalse(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").holds(aigPred)).isFalse(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").holds(aigPred)).isFalse(); + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").holds(aigPred)).isFalse(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").holds(aigPred)).isFalse(); + assertThat(_c.p.parse("a | b | (~x & ~y)").holds(aigPred)).isFalse(); final Formula or = _c.p.parse("m | n | o"); or.transform(aigNonCaching); final Formula and = _c.p.parse("m & n & o"); @@ -109,20 +108,20 @@ public void testNot(final FormulaContext _c) throws ParserException { final AIGTransformation aigCaching = new AIGTransformation(_c.f); final AIGTransformation aigNonCaching = new AIGTransformation(_c.f, null); - Assertions.assertThat(_c.p.parse("~a").transform(aigCaching)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(aigCaching)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").transform(aigCaching)).isEqualTo(_c.p.parse("a & ~b")); - Assertions.assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").transform(aigCaching)) + assertThat(_c.p.parse("~a").transform(aigCaching)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(aigCaching)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").transform(aigCaching)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").transform(aigCaching)) .isEqualTo(_c.p.parse("(~a & ~b) & ~(~x & ~y)")); - Assertions.assertThat(_c.p.parse("~(a <=> b)").transform(aigCaching)) + assertThat(_c.p.parse("~(a <=> b)").transform(aigCaching)) .isEqualTo(_c.p.parse("~(~(a & ~b) & ~(~a & b))")); - Assertions.assertThat(_c.p.parse("~(~(a | b) <=> ~(x | y))").transform(aigCaching)) + assertThat(_c.p.parse("~(~(a | b) <=> ~(x | y))").transform(aigCaching)) .isEqualTo(_c.p.parse("~(~(~a & ~b & ~(~x & ~y)) & ~((a | b) & ~(x | y)))")); - Assertions.assertThat(_c.p.parse("~(a & b & ~x & ~y)").transform(aigCaching)) + assertThat(_c.p.parse("~(a & b & ~x & ~y)").transform(aigCaching)) .isEqualTo(_c.p.parse("~(a & b & ~x & ~y)")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(aigCaching)) + assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(aigCaching)) .isEqualTo(_c.p.parse("~a & ~b & x & y")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(aigCaching)) + assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(aigCaching)) .isEqualTo(_c.p.parse("~a & ~b & x & y")); // test caching final Formula not = _c.p.parse("~(m | n)"); not.transform(aigNonCaching); diff --git a/src/test/java/com/booleworks/logicng/transformations/AnonymizerTest.java b/src/test/java/com/booleworks/logicng/transformations/AnonymizerTest.java index df8e1ea5..3f2c2b03 100644 --- a/src/test/java/com/booleworks/logicng/transformations/AnonymizerTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/AnonymizerTest.java @@ -4,6 +4,8 @@ package com.booleworks.logicng.transformations; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.datastructures.Substitution; import com.booleworks.logicng.formulas.Formula; import com.booleworks.logicng.formulas.FormulaContext; @@ -22,15 +24,15 @@ public class AnonymizerTest extends TestWithFormulaContext { @MethodSource("contexts") public void testSimpleFormulasDefault(final FormulaContext _c) throws ParserException { final Anonymizer anonymizer = new Anonymizer(_c.f); - Assertions.assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("v0")); - Assertions.assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~v0")); - Assertions.assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("v0 => ~v1")); - Assertions.assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("v0 <=> ~v1")); - Assertions.assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) + assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); + assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("v0")); + assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~v0")); + assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("v0 => ~v1")); + assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("v0 <=> ~v1")); + assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) .isEqualTo(_c.p.parse("v0 | v1 | ~v3 | v2")); - Assertions.assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) + assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) .isEqualTo(_c.p.parse("v0 & v1 & v2 & ~v3")); } @@ -38,16 +40,16 @@ public void testSimpleFormulasDefault(final FormulaContext _c) throws ParserExce @MethodSource("contexts") public void testSimpleFormulasOwnPrefix(final FormulaContext _c) throws ParserException { final Anonymizer anonymizer = new Anonymizer(_c.f, "var"); - Assertions.assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var0")); - Assertions.assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var0")); - Assertions.assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 => ~var1")); - Assertions.assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 <=> ~var1")); - Assertions.assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 <=> ~var1")); - Assertions.assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) + assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); + assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var0")); + assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var0")); + assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 => ~var1")); + assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 <=> ~var1")); + assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var0 <=> ~var1")); + assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) .isEqualTo(_c.p.parse("var0 | var1 | ~var3 | var2")); - Assertions.assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) + assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) .isEqualTo(_c.p.parse("var0 & var1 & var2 & ~var3")); } @@ -55,15 +57,15 @@ public void testSimpleFormulasOwnPrefix(final FormulaContext _c) throws ParserEx @MethodSource("contexts") public void testSimpleFormulasOwnPrefixAndCounter(final FormulaContext _c) throws ParserException { final Anonymizer anonymizer = new Anonymizer(_c.f, "var", 10); - Assertions.assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var10")); - Assertions.assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var10")); - Assertions.assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 => ~var11")); - Assertions.assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 <=> ~var11")); - Assertions.assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) + assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); + assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var10")); + assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var10")); + assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 => ~var11")); + assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 <=> ~var11")); + assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) .isEqualTo(_c.p.parse("var10 | var11 | ~var13 | var12")); - Assertions.assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) + assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) .isEqualTo(_c.p.parse("var10 & var11 & var12 & ~var13")); } @@ -71,15 +73,15 @@ public void testSimpleFormulasOwnPrefixAndCounter(final FormulaContext _c) throw @MethodSource("contexts") public void testSimpleFormulasOwnPrefixAndCounterWithoutCache(final FormulaContext _c) throws ParserException { final Anonymizer anonymizer = new Anonymizer(_c.f, "var", 10); - Assertions.assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var10")); - Assertions.assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var10")); - Assertions.assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 => ~var11")); - Assertions.assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 <=> ~var11")); - Assertions.assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) + assertThat(_c.p.parse("$true").transform(anonymizer)).isEqualTo(_c.p.parse("$true")); + assertThat(_c.p.parse("$false").transform(anonymizer)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("A").transform(anonymizer)).isEqualTo(_c.p.parse("var10")); + assertThat(_c.p.parse("~A").transform(anonymizer)).isEqualTo(_c.p.parse("~var10")); + assertThat(_c.p.parse("A => ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 => ~var11")); + assertThat(_c.p.parse("A <=> ~B").transform(anonymizer)).isEqualTo(_c.p.parse("var10 <=> ~var11")); + assertThat(_c.p.parse("A | B | ~D | C").transform(anonymizer)) .isEqualTo(_c.p.parse("var10 | var11 | ~var13 | var12")); - Assertions.assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) + assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) .isEqualTo(_c.p.parse("var10 & var11 & var12 & ~var13")); } @@ -87,19 +89,19 @@ public void testSimpleFormulasOwnPrefixAndCounterWithoutCache(final FormulaConte @MethodSource("contexts") public void testGetSubstitution(final FormulaContext _c) throws ParserException { final Anonymizer anonymizer = new Anonymizer(_c.f, "v", 0); - Assertions.assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution()); - Assertions.assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) + assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution()); + assertThat(_c.p.parse("A & B & C & ~D").transform(anonymizer)) .isEqualTo(_c.p.parse("v0 & v1 & v2 & ~v3")); final HashMap mapping = new HashMap<>(); mapping.put(_c.f.variable("A"), _c.f.variable("v0")); mapping.put(_c.f.variable("B"), _c.f.variable("v1")); mapping.put(_c.f.variable("C"), _c.f.variable("v2")); mapping.put(_c.f.variable("D"), _c.f.variable("v3")); - Assertions.assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution(mapping)); - Assertions.assertThat(_c.p.parse("E & A & C & ~F").transform(anonymizer)) + assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution(mapping)); + assertThat(_c.p.parse("E & A & C & ~F").transform(anonymizer)) .isEqualTo(_c.p.parse("v4 & v0 & v2 & ~v5")); mapping.put(_c.f.variable("E"), _c.f.variable("v4")); mapping.put(_c.f.variable("F"), _c.f.variable("v5")); - Assertions.assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution(mapping)); + assertThat(anonymizer.getSubstitution()).isEqualTo(new Substitution(mapping)); } } diff --git a/src/test/java/com/booleworks/logicng/transformations/FormulaFactoryImporterTest.java b/src/test/java/com/booleworks/logicng/transformations/FormulaFactoryImporterTest.java index 1657c03b..4ce7924f 100644 --- a/src/test/java/com/booleworks/logicng/transformations/FormulaFactoryImporterTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/FormulaFactoryImporterTest.java @@ -45,20 +45,20 @@ public void testSameFactory() { public void testConstants() { assertThat(c.verum.factory()).isSameAs(myF); assertThat(c.falsum.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.verum).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.falsum).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.verum)).isEqualTo(c.verum); - Assertions.assertThat(imp(c.falsum)).isEqualTo(c.falsum); + assertThat(imp(c.verum).factory()).isSameAs(myG); + assertThat(imp(c.falsum).factory()).isSameAs(myG); + assertThat(imp(c.verum)).isEqualTo(c.verum); + assertThat(imp(c.falsum)).isEqualTo(c.falsum); } @Test public void testLiteral() { assertThat(c.a.factory()).isSameAs(myF); assertThat(c.na.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.a).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.na).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.a)).isEqualTo(c.a); - Assertions.assertThat(imp(c.na)).isEqualTo(c.na); + assertThat(imp(c.a).factory()).isSameAs(myG); + assertThat(imp(c.na).factory()).isSameAs(myG); + assertThat(imp(c.a)).isEqualTo(c.a); + assertThat(imp(c.na)).isEqualTo(c.na); assertThat(myG.statistics().positiveLiterals()).isEqualTo(1); assertThat(myG.statistics().negativeLiterals()).isEqualTo(1); } @@ -67,10 +67,10 @@ public void testLiteral() { public void testNot() { assertThat(c.not1.factory()).isSameAs(myF); assertThat(c.not2.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.not1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.not2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.not1)).isEqualTo(c.not1); - Assertions.assertThat(imp(c.not2)).isEqualTo(c.not2); + assertThat(imp(c.not1).factory()).isSameAs(myG); + assertThat(imp(c.not2).factory()).isSameAs(myG); + assertThat(imp(c.not1)).isEqualTo(c.not1); + assertThat(imp(c.not2)).isEqualTo(c.not2); assertThat(myG.statistics().positiveLiterals()).isEqualTo(4); assertThat(myG.statistics().negativeLiterals()).isEqualTo(0); assertThat(myG.statistics().conjunctions2()).isEqualTo(1); @@ -84,14 +84,14 @@ public void testImplication() { assertThat(c.imp2.factory()).isSameAs(myF); assertThat(c.imp3.factory()).isSameAs(myF); assertThat(c.imp4.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.imp1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.imp2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.imp3).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.imp4).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.imp1)).isEqualTo(c.imp1); - Assertions.assertThat(imp(c.imp2)).isEqualTo(c.imp2); - Assertions.assertThat(imp(c.imp3)).isEqualTo(c.imp3); - Assertions.assertThat(imp(c.imp4)).isEqualTo(c.imp4); + assertThat(imp(c.imp1).factory()).isSameAs(myG); + assertThat(imp(c.imp2).factory()).isSameAs(myG); + assertThat(imp(c.imp3).factory()).isSameAs(myG); + assertThat(imp(c.imp4).factory()).isSameAs(myG); + assertThat(imp(c.imp1)).isEqualTo(c.imp1); + assertThat(imp(c.imp2)).isEqualTo(c.imp2); + assertThat(imp(c.imp3)).isEqualTo(c.imp3); + assertThat(imp(c.imp4)).isEqualTo(c.imp4); assertThat(myG.statistics().positiveLiterals()).isEqualTo(4); assertThat(myG.statistics().negativeLiterals()).isEqualTo(4); assertThat(myG.statistics().conjunctions2()).isEqualTo(1); @@ -107,14 +107,14 @@ public void testEquivalence() { assertThat(c.eq2.factory()).isSameAs(myF); assertThat(c.eq3.factory()).isSameAs(myF); assertThat(c.eq4.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.eq1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.eq2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.eq3).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.eq4).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.eq1)).isEqualTo(c.eq1); - Assertions.assertThat(imp(c.eq2)).isEqualTo(c.eq2); - Assertions.assertThat(imp(c.eq3)).isEqualTo(c.eq3); - Assertions.assertThat(imp(c.eq4)).isEqualTo(c.eq4); + assertThat(imp(c.eq1).factory()).isSameAs(myG); + assertThat(imp(c.eq2).factory()).isSameAs(myG); + assertThat(imp(c.eq3).factory()).isSameAs(myG); + assertThat(imp(c.eq4).factory()).isSameAs(myG); + assertThat(imp(c.eq1)).isEqualTo(c.eq1); + assertThat(imp(c.eq2)).isEqualTo(c.eq2); + assertThat(imp(c.eq3)).isEqualTo(c.eq3); + assertThat(imp(c.eq4)).isEqualTo(c.eq4); assertThat(myG.statistics().positiveLiterals()).isEqualTo(4); assertThat(myG.statistics().negativeLiterals()).isEqualTo(2); assertThat(myG.statistics().conjunctions2()).isEqualTo(1); @@ -129,12 +129,12 @@ public void testOr() { assertThat(c.or1.factory()).isSameAs(myF); assertThat(c.or2.factory()).isSameAs(myF); assertThat(c.or3.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.or1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.or2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.or3).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.or1)).isEqualTo(c.or1); - Assertions.assertThat(imp(c.or2)).isEqualTo(c.or2); - Assertions.assertThat(imp(c.or3)).isEqualTo(c.or3); + assertThat(imp(c.or1).factory()).isSameAs(myG); + assertThat(imp(c.or2).factory()).isSameAs(myG); + assertThat(imp(c.or3).factory()).isSameAs(myG); + assertThat(imp(c.or1)).isEqualTo(c.or1); + assertThat(imp(c.or2)).isEqualTo(c.or2); + assertThat(imp(c.or3)).isEqualTo(c.or3); assertThat(myG.statistics().positiveLiterals()).isEqualTo(4); assertThat(myG.statistics().negativeLiterals()).isEqualTo(4); assertThat(myG.statistics().conjunctions2()).isEqualTo(2); @@ -149,12 +149,12 @@ public void testAnd() { assertThat(c.and1.factory()).isSameAs(myF); assertThat(c.and2.factory()).isSameAs(myF); assertThat(c.and3.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.and1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.and2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.and3).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.and1)).isEqualTo(c.and1); - Assertions.assertThat(imp(c.and2)).isEqualTo(c.and2); - Assertions.assertThat(imp(c.and3)).isEqualTo(c.and3); + assertThat(imp(c.and1).factory()).isSameAs(myG); + assertThat(imp(c.and2).factory()).isSameAs(myG); + assertThat(imp(c.and3).factory()).isSameAs(myG); + assertThat(imp(c.and1)).isEqualTo(c.and1); + assertThat(imp(c.and2)).isEqualTo(c.and2); + assertThat(imp(c.and3)).isEqualTo(c.and3); assertThat(myG.statistics().positiveLiterals()).isEqualTo(4); assertThat(myG.statistics().negativeLiterals()).isEqualTo(4); assertThat(myG.statistics().conjunctions2()).isEqualTo(3); @@ -171,16 +171,16 @@ public void testPBC() { assertThat(c.pbc3.factory()).isSameAs(myF); assertThat(c.pbc4.factory()).isSameAs(myF); assertThat(c.pbc5.factory()).isSameAs(myF); - Assertions.assertThat(imp(c.pbc1).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.pbc2).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.pbc3).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.pbc4).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.pbc5).factory()).isSameAs(myG); - Assertions.assertThat(imp(c.pbc1)).isEqualTo(c.pbc1); - Assertions.assertThat(imp(c.pbc2)).isEqualTo(c.pbc2); - Assertions.assertThat(imp(c.pbc3)).isEqualTo(c.pbc3); - Assertions.assertThat(imp(c.pbc4)).isEqualTo(c.pbc4); - Assertions.assertThat(imp(c.pbc5)).isEqualTo(c.pbc5); + assertThat(imp(c.pbc1).factory()).isSameAs(myG); + assertThat(imp(c.pbc2).factory()).isSameAs(myG); + assertThat(imp(c.pbc3).factory()).isSameAs(myG); + assertThat(imp(c.pbc4).factory()).isSameAs(myG); + assertThat(imp(c.pbc5).factory()).isSameAs(myG); + assertThat(imp(c.pbc1)).isEqualTo(c.pbc1); + assertThat(imp(c.pbc2)).isEqualTo(c.pbc2); + assertThat(imp(c.pbc3)).isEqualTo(c.pbc3); + assertThat(imp(c.pbc4)).isEqualTo(c.pbc4); + assertThat(imp(c.pbc5)).isEqualTo(c.pbc5); assertThat(myG.statistics().positiveLiterals()).isEqualTo(3); assertThat(myG.statistics().negativeLiterals()).isEqualTo(0); assertThat(myG.statistics().conjunctions2()).isEqualTo(0); diff --git a/src/test/java/com/booleworks/logicng/transformations/UnitPropagationTest.java b/src/test/java/com/booleworks/logicng/transformations/UnitPropagationTest.java index b7961077..65529c5a 100644 --- a/src/test/java/com/booleworks/logicng/transformations/UnitPropagationTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/UnitPropagationTest.java @@ -54,7 +54,7 @@ public void testPropagations(final FormulaContext _c) throws ParserException { assertThat(_c.f.and(_c.or1, _c.x).transform(unitPropagation)).isEqualTo(_c.x); assertThat(_c.f.or(_c.and1, _c.a).transform(unitPropagation)).isEqualTo(_c.a); assertThat(_c.f.or(_c.or1, _c.x).transform(unitPropagation)).isEqualTo(_c.or1); - Assertions.assertThat(_c.p.parse( + assertThat(_c.p.parse( "(a | b | ~c) & (~a | ~d) & (~c | d) & (~b | e | ~f | g) & (e | f | g | h) & (e | ~f | ~g | h) & f & c") .transform(unitPropagation)).isEqualTo(_c.p.parse("(e | g) & (e | ~g | h) & f & c & d & ~a & b")); } diff --git a/src/test/java/com/booleworks/logicng/transformations/cnf/BDDCNFTest.java b/src/test/java/com/booleworks/logicng/transformations/cnf/BDDCNFTest.java index 28c48b50..e2e41bce 100644 --- a/src/test/java/com/booleworks/logicng/transformations/cnf/BDDCNFTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/cnf/BDDCNFTest.java @@ -12,7 +12,6 @@ import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; import com.booleworks.logicng.testutils.TestUtil; -import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -42,25 +41,25 @@ public void testBinaryOperators(final FormulaContext _c) { final BDDCNFTransformation bddcnf = new BDDCNFTransformation(_c.f); assertThat(_c.imp1.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp1, _c.imp1.transform(bddcnf), _c.imp1.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp1, _c.imp1.transform(bddcnf), _c.imp1.variables(_c.f))) .isTrue(); assertThat(_c.imp2.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp2, _c.imp2.transform(bddcnf), _c.imp2.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp2, _c.imp2.transform(bddcnf), _c.imp2.variables(_c.f))) .isTrue(); assertThat(_c.imp3.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp3, _c.imp3.transform(bddcnf), _c.imp3.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp3, _c.imp3.transform(bddcnf), _c.imp3.variables(_c.f))) .isTrue(); assertThat(_c.eq1.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq1, _c.eq1.transform(bddcnf), _c.eq1.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq1, _c.eq1.transform(bddcnf), _c.eq1.variables(_c.f))) .isTrue(); assertThat(_c.eq2.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq2, _c.eq2.transform(bddcnf), _c.eq2.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq2, _c.eq2.transform(bddcnf), _c.eq2.variables(_c.f))) .isTrue(); assertThat(_c.eq3.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq3, _c.eq3.transform(bddcnf), _c.eq3.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq3, _c.eq3.transform(bddcnf), _c.eq3.variables(_c.f))) .isTrue(); assertThat(_c.eq4.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq4, _c.eq4.transform(bddcnf), _c.eq4.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq4, _c.eq4.transform(bddcnf), _c.eq4.variables(_c.f))) .isTrue(); } @@ -75,11 +74,11 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -94,11 +93,11 @@ public void testNAryOperatorsWithExternalFactory(final FormulaContext _c) throws final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -113,11 +112,11 @@ public void testNAryOperatorsWithExternalFactory2(final FormulaContext _c) throw final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(transformation).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -125,26 +124,26 @@ public void testNAryOperatorsWithExternalFactory2(final FormulaContext _c) throw public void testNot(final FormulaContext _c) throws ParserException { final BDDCNFTransformation bddcnf = new BDDCNFTransformation(_c.f); - Assertions.assertThat(_c.p.parse("~a").transform(bddcnf)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(bddcnf)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").transform(bddcnf)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~a").transform(bddcnf)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(bddcnf)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").transform(bddcnf)).isEqualTo(_c.p.parse("a & ~b")); final Formula f1 = _c.p.parse("~(~(a | b) => ~(x | y))"); final Formula f2 = _c.p.parse("~(a <=> b)"); final Formula f3 = _c.p.parse("~(~(a | b) <=> ~(x | y))"); final Formula f4 = _c.p.parse("~(a & b & ~x & ~y)"); final Formula f5 = _c.p.parse("~(a | b | ~x | ~y)"); assertThat(f1.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); assertThat(f4.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f4, f4.transform(bddcnf), f4.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f4, f4.transform(bddcnf), f4.variables(_c.f))).isTrue(); assertThat(f5.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f5, f5.transform(bddcnf), f5.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f5, f5.transform(bddcnf), f5.variables(_c.f))).isTrue(); assertThat(f5.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f5, f5.transform(bddcnf), f5.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f5, f5.transform(bddcnf), f5.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -157,12 +156,12 @@ public void testCC(final FormulaContext _c) throws ParserException { final Formula f3 = _c.p.parse("(1 * b + 1 * c + 1 * d <= 1)"); final Formula f4 = _c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)"); assertThat(f1.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bddcnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bddcnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bddcnf), f3.variables(_c.f))).isTrue(); assertThat(f4.transform(bddcnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f4, f4.transform(bddcnf), f4.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f4, f4.transform(bddcnf), f4.variables(_c.f))).isTrue(); } } diff --git a/src/test/java/com/booleworks/logicng/transformations/cnf/CNFSubsumptionTest.java b/src/test/java/com/booleworks/logicng/transformations/cnf/CNFSubsumptionTest.java index ee67e603..d849b507 100644 --- a/src/test/java/com/booleworks/logicng/transformations/cnf/CNFSubsumptionTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/cnf/CNFSubsumptionTest.java @@ -28,18 +28,18 @@ public class CNFSubsumptionTest extends TestWithFormulaContext { @MethodSource("contexts") public void testSimpleCNFSubsumption(final FormulaContext _c) throws ParserException { final CNFSubsumption s = new CNFSubsumption(_c.f); - Assertions.assertThat(s.apply(_c.p.parse("$false"))).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(s.apply(_c.p.parse("$true"))).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(s.apply(_c.p.parse("a"))).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(s.apply(_c.p.parse("~a"))).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(s.apply(_c.p.parse("a | b | c"))).isEqualTo(_c.p.parse("a | b | c")); - Assertions.assertThat(s.apply(_c.p.parse("a & b & c"))).isEqualTo(_c.p.parse("a & b & c")); - Assertions.assertThat(s.apply(_c.p.parse("a & (a | b)"))).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(s.apply(_c.p.parse("(a | b) & (a | b | c)"))).isEqualTo(_c.p.parse("a | b")); - Assertions.assertThat(s.apply(_c.p.parse("a & (a | b) & (a | b | c)"))).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(s.apply(_c.p.parse("a & (a | b) & b"))).isEqualTo(_c.p.parse("a & b")); - Assertions.assertThat(s.apply(_c.p.parse("a & (a | b) & c & (c | b)"))).isEqualTo(_c.p.parse("a & c")); - Assertions.assertThat(s.apply(_c.p.parse("(a | b) & (a | c) & (a | b | c)"))) + assertThat(s.apply(_c.p.parse("$false"))).isEqualTo(_c.p.parse("$false")); + assertThat(s.apply(_c.p.parse("$true"))).isEqualTo(_c.p.parse("$true")); + assertThat(s.apply(_c.p.parse("a"))).isEqualTo(_c.p.parse("a")); + assertThat(s.apply(_c.p.parse("~a"))).isEqualTo(_c.p.parse("~a")); + assertThat(s.apply(_c.p.parse("a | b | c"))).isEqualTo(_c.p.parse("a | b | c")); + assertThat(s.apply(_c.p.parse("a & b & c"))).isEqualTo(_c.p.parse("a & b & c")); + assertThat(s.apply(_c.p.parse("a & (a | b)"))).isEqualTo(_c.p.parse("a")); + assertThat(s.apply(_c.p.parse("(a | b) & (a | b | c)"))).isEqualTo(_c.p.parse("a | b")); + assertThat(s.apply(_c.p.parse("a & (a | b) & (a | b | c)"))).isEqualTo(_c.p.parse("a")); + assertThat(s.apply(_c.p.parse("a & (a | b) & b"))).isEqualTo(_c.p.parse("a & b")); + assertThat(s.apply(_c.p.parse("a & (a | b) & c & (c | b)"))).isEqualTo(_c.p.parse("a & c")); + assertThat(s.apply(_c.p.parse("(a | b) & (a | c) & (a | b | c)"))) .isEqualTo(_c.p.parse("(a | b) & (a | c)")); } @@ -47,7 +47,7 @@ public void testSimpleCNFSubsumption(final FormulaContext _c) throws ParserExcep @MethodSource("contexts") public void testLargeCNFSubsumption(final FormulaContext _c) throws ParserException { final CNFSubsumption s = new CNFSubsumption(_c.f); - Assertions.assertThat(s.apply(_c.p.parse("(a | b | c | d) & (a | b | c | e) & (a | b | c)"))) + assertThat(s.apply(_c.p.parse("(a | b | c | d) & (a | b | c | e) & (a | b | c)"))) .isEqualTo(_c.p.parse("(a | b | c)")); Assertions .assertThat( @@ -57,9 +57,9 @@ public void testLargeCNFSubsumption(final FormulaContext _c) throws ParserExcept .assertThat( s.apply(_c.p.parse("(a | b) & (a | c) & (a | b | c) & (a | ~b | c) & (a | b | ~c) & (b | c)"))) .isEqualTo(_c.p.parse("(a | b) & (a | c) & (b | c)")); - Assertions.assertThat(s.apply(_c.p.parse("a & ~b & (c | d) & (~a | ~b | ~c) & (b | c | d) & (a | b | c | d)"))) + assertThat(s.apply(_c.p.parse("a & ~b & (c | d) & (~a | ~b | ~c) & (b | c | d) & (a | b | c | d)"))) .isEqualTo(_c.p.parse("a & ~b & (c | d)")); - Assertions.assertThat(s.apply(_c.p.parse("(a | b | c | d | e | f | g) & (b | d | f) & (a | c | e | g)"))) + assertThat(s.apply(_c.p.parse("(a | b | c | d | e | f | g) & (b | d | f) & (a | c | e | g)"))) .isEqualTo(_c.p.parse("(b | d | f) & (a | c | e | g)")); } diff --git a/src/test/java/com/booleworks/logicng/transformations/cnf/CNFTest.java b/src/test/java/com/booleworks/logicng/transformations/cnf/CNFTest.java index b4841356..8747e34c 100644 --- a/src/test/java/com/booleworks/logicng/transformations/cnf/CNFTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/cnf/CNFTest.java @@ -12,8 +12,9 @@ import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.events.FactorizationCreatedClauseEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.io.parsers.ParserException; import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; @@ -28,84 +29,91 @@ public class CNFTest extends TestWithFormulaContext { @ParameterizedTest @MethodSource("contexts") public void testConstants(final FormulaContext _c) { - final CNFFactorization cnf = new CNFFactorization(_c.f, handler); + final CNFFactorization cnf = new CNFFactorization(_c.f); - assertThat(_c.verum.transform(cnf)).isEqualTo(_c.verum); - assertThat(_c.falsum.transform(cnf)).isEqualTo(_c.falsum); + assertThat(_c.verum.transform(cnf, handler).getResult()).isEqualTo(_c.verum); + assertThat(_c.falsum.transform(cnf, handler).getResult()).isEqualTo(_c.falsum); } @ParameterizedTest @MethodSource("contexts") public void testLiterals(final FormulaContext _c) { - final CNFFactorization cnf = new CNFFactorization(_c.f, handler); + final CNFFactorization cnf = new CNFFactorization(_c.f); - assertThat(_c.a.transform(cnf)).isEqualTo(_c.a); - assertThat(_c.na.transform(cnf)).isEqualTo(_c.na); + assertThat(_c.a.transform(cnf, handler).getResult()).isEqualTo(_c.a); + assertThat(_c.na.transform(cnf, handler).getResult()).isEqualTo(_c.na); } @ParameterizedTest @MethodSource("contexts") public void testBinaryOperators(final FormulaContext _c) throws ParserException { - final CNFFactorization cnf = new CNFFactorization(_c.f, handler); - - assertThat(_c.imp1.transform(cnf)).isEqualTo(_c.p.parse("~a | b")); - assertThat(_c.imp2.transform(cnf)).isEqualTo(_c.p.parse("a | ~b")); - assertThat(_c.imp3.transform(cnf)).isEqualTo(_c.p.parse("~a | ~b | x | y")); - assertThat(_c.eq1.transform(cnf)).isEqualTo(_c.p.parse("(a | ~b) & (~a | b)")); - assertThat(_c.eq2.transform(cnf)).isEqualTo(_c.p.parse("(~a | b) & (a | ~b)")); - assertThat(_c.imp1.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.imp2.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.imp3.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.eq1.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.eq1.transform(cnf).isDNF(_c.f)).isFalse(); - assertThat(_c.eq2.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.eq2.transform(cnf).isDNF(_c.f)).isFalse(); + final CNFFactorization cnf = new CNFFactorization(_c.f); + + assertThat(_c.imp1.transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("~a | b")); + assertThat(_c.imp2.transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("a | ~b")); + assertThat(_c.imp3.transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("~a | ~b | x | y")); + assertThat(_c.eq1.transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("(a | ~b) & (~a | b)")); + assertThat(_c.eq2.transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("(~a | b) & (a | ~b)")); + assertThat(_c.imp1.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.imp2.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.imp3.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.eq1.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.eq1.transform(cnf, handler).getResult().isDNF(_c.f)).isFalse(); + assertThat(_c.eq2.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.eq2.transform(cnf, handler).getResult().isDNF(_c.f)).isFalse(); } @ParameterizedTest @MethodSource("contexts") public void testNAryOperators(final FormulaContext _c) throws ParserException { - final CNFFactorization cnf = new CNFFactorization(_c.f, handler); + final CNFFactorization cnf = new CNFFactorization(_c.f); - assertThat(_c.and1.transform(cnf)).isEqualTo(_c.and1); - assertThat(_c.or1.transform(cnf)).isEqualTo(_c.or1); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf)) + assertThat(_c.and1.transform(cnf, handler).getResult()).isEqualTo(_c.and1); + assertThat(_c.or1.transform(cnf, handler).getResult()).isEqualTo(_c.or1); + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf, handler) + .getResult()) .isEqualTo(_c.p.parse("~a & ~b & c & (~x | y) & (~w | z)")); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf)) + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("(~a | ~b | c | ~x) & (~a | ~b | c | y)")); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf)) + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("(a | b | ~x) & (a | b | ~y)")); - assertThat(_c.and1.transform(cnf).isCNF(_c.f)).isTrue(); - assertThat(_c.or1.transform(cnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf).isDNF(_c.f)).isFalse(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf).isDNF(_c.f)).isFalse(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf).isCNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf).isDNF(_c.f)).isFalse(); + assertThat(_c.and1.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.or1.transform(cnf, handler).getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf, handler) + .getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(cnf, handler) + .getResult().isDNF(_c.f)).isFalse(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf, handler) + .getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(cnf, handler) + .getResult().isDNF(_c.f)).isFalse(); + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf, handler) + .getResult().isCNF(_c.f)).isTrue(); + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(cnf, handler) + .getResult().isDNF(_c.f)).isFalse(); } @ParameterizedTest @MethodSource("contexts") public void testNot(final FormulaContext _c) throws ParserException { - final CNFFactorization cnf = new CNFFactorization(_c.f, handler); + final CNFFactorization cnf = new CNFFactorization(_c.f); final TestFactorizationHandler handler2 = new TestFactorizationHandler(); - final CNFFactorization cnf2 = new CNFFactorization(_c.f, handler2, new HashMap<>()); - Assertions.assertThat(_c.p.parse("~a2").transform(cnf)).isEqualTo(_c.p.parse("~a2")); - Assertions.assertThat(_c.p.parse("~~a2").transform(cnf)).isEqualTo(_c.p.parse("a2")); - Assertions.assertThat(_c.p.parse("~(a2 => b2)").transform(cnf)).isEqualTo(_c.p.parse("a2 & ~b2")); - Assertions.assertThat(_c.p.parse("~(~(a2 | b2) => ~(x2 | y2))").transform(cnf)) + final CNFFactorization cnf2 = new CNFFactorization(_c.f, new HashMap<>()); + assertThat(_c.p.parse("~a2").transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("~a2")); + assertThat(_c.p.parse("~~a2").transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("a2")); + assertThat(_c.p.parse("~(a2 => b2)").transform(cnf, handler).getResult()).isEqualTo(_c.p.parse("a2 & ~b2")); + assertThat(_c.p.parse("~(~(a2 | b2) => ~(x2 | y2))").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("~a2 & ~b2 & (x2 | y2)")); - Assertions.assertThat(_c.p.parse("~(a2 <=> b2)").transform(cnf)) + assertThat(_c.p.parse("~(a2 <=> b2)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("(~a2 | ~b2) & (a2 | b2)")); - Assertions.assertThat(_c.p.parse("~(~(a2 | b2) <=> ~(x2 | y2))").transform(cnf2)) + assertThat(_c.p.parse("~(~(a2 | b2) <=> ~(x2 | y2))").transform(cnf2, handler2).getResult()) .isEqualTo(_c.p.parse("(a2 | b2 | x2 | y2) & (~a2 | ~x2) & (~a2 | ~y2) & (~b2 | ~x2) & (~b2 | ~y2)")); - Assertions.assertThat(_c.p.parse("~(a2 & b2 & ~x2 & ~y2)").transform(cnf)) + assertThat(_c.p.parse("~(a2 & b2 & ~x2 & ~y2)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("~a2 | ~b2 | x2 | y2")); - Assertions.assertThat(_c.p.parse("~(a2 | b2 | ~x2 | ~y2)").transform(cnf)) + assertThat(_c.p.parse("~(a2 | b2 | ~x2 | ~y2)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("~a2 & ~b2 & x2 & y2")); - Assertions.assertThat(_c.p.parse("~(a2 | b2 | ~x2 | ~y2)").transform(cnf)) + assertThat(_c.p.parse("~(a2 | b2 | ~x2 | ~y2)").transform(cnf, handler).getResult()) .isEqualTo(_c.p.parse("~a2 & ~b2 & x2 & y2")); assertThat(handler2.distCount).isEqualTo(10); assertThat(handler2.clauseCount).isEqualTo(7); @@ -115,11 +123,11 @@ public void testNot(final FormulaContext _c) throws ParserException { @ParameterizedTest @MethodSource("contexts") public void testCC(final FormulaContext _c) throws ParserException { - Assertions.assertThat(_c.p.parse("a <=> (1 * b <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(1 * b <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").cnf(_c.f)) + assertThat(_c.p.parse("a <=> (1 * b <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(1 * b <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").cnf(_c.f)) .isEqualTo(_c.p.parse("(~b | ~c) & (~b | ~d) & (~c | ~d)")); - Assertions.assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse(String.format( + assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").cnf(_c.f)).isEqualTo(_c.p.parse(String.format( "(d | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | d | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_4 | @AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_2 | @AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_4 | ~@AUX_%1$s_CC_2) & (c | @AUX_%1$s_CC_3 | @AUX_%1$s_CC_5) & (b | @AUX_%1$s_CC_3 | @AUX_%1$s_CC_5) & (b | c | @AUX_%1$s_CC_5) & (~@AUX_%1$s_CC_5 | @AUX_%1$s_CC_2) & ~@AUX_%1$s_CC_0", _c.f.name()))); } @@ -134,12 +142,7 @@ public void testWithHandler(final FormulaContext _c) throws ParserException { private int clauses = 0; @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == FACTORIZATION_STARTED) { aborted = false; dists = 0; @@ -154,33 +157,25 @@ public boolean shouldResume(final LogicNGEvent event) { return !aborted; } }; - final CNFFactorization factorization = new CNFFactorization(_c.f, handler, null); - Formula cnf = factorization.apply(formula); - assertThat(handler.isAborted()).isTrue(); - assertThat(cnf).isNull(); + final CNFFactorization factorization = new CNFFactorization(_c.f, null); + LNGResult cnf = factorization.apply(formula, handler); + assertThat(cnf.isSuccess()).isFalse(); + assertThat(cnf.getResult()).isNull(); formula = _c.p.parse("~(a | b)"); - cnf = factorization.apply(formula); - assertThat(handler.isAborted()).isFalse(); - assertThat(cnf).isNotNull(); + cnf = factorization.apply(formula, handler); + assertThat(cnf.isSuccess()).isTrue(); + assertThat(cnf.getResult()).isNotNull(); } private static class TestFactorizationHandler implements ComputationHandler { - - private boolean aborted; private int distCount = 0; private int clauseCount = 0; private long longestClause = 0; @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == FACTORIZATION_STARTED) { - aborted = false; distCount = 0; clauseCount = 0; longestClause = 0; diff --git a/src/test/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTest.java b/src/test/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTest.java index 92eccdeb..69d123e6 100644 --- a/src/test/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/cnf/PlaistedGreenbaumTest.java @@ -81,8 +81,8 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { public void testNotNary(final FormulaContext _c) throws ParserException { final PlaistedGreenbaumTransformation pg = new PlaistedGreenbaumTransformation(_c.f, 0); - Assertions.assertThat(_c.p.parse("~a").transform(pg)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(pg)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~a").transform(pg)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(pg)).isEqualTo(_c.p.parse("a")); final Formula f0 = _c.p.parse("~(~a | b)"); final Formula f1 = _c.p.parse("~((a | b) | ~(x | y))"); final Formula f2 = _c.p.parse("~(a & b | ~a & ~b)"); @@ -113,8 +113,8 @@ public void testNotNary(final FormulaContext _c) throws ParserException { public void testNotBinary(final FormulaContext _c) throws ParserException { final PlaistedGreenbaumTransformation pg = new PlaistedGreenbaumTransformation(_c.f, 0); - Assertions.assertThat(_c.p.parse("~a").transform(pg)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(pg)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~a").transform(pg)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(pg)).isEqualTo(_c.p.parse("a")); final Formula f1 = _c.p.parse("~(~(a | b) => ~(x | y))"); final Formula f2 = _c.p.parse("~(a <=> b)"); final Formula f3 = _c.p.parse("~(~(a | b) <=> ~(x | y))"); @@ -131,11 +131,11 @@ public void testNotBinary(final FormulaContext _c) throws ParserException { public void testCC(final FormulaContext _c) throws ParserException { final PlaistedGreenbaumTransformation pg = new PlaistedGreenbaumTransformation(_c.f, 0); - Assertions.assertThat(_c.p.parse("a <=> (1 * b <= 1)").transform(pg)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(1 * b <= 1)").transform(pg)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").transform(pg)) + assertThat(_c.p.parse("a <=> (1 * b <= 1)").transform(pg)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(1 * b <= 1)").transform(pg)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").transform(pg)) .isEqualTo(_c.p.parse("(~b | ~c) & (~b | ~d) & (~c | ~d)")); - Assertions.assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").transform(pg)).isEqualTo(_c.p.parse( + assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").transform(pg)).isEqualTo(_c.p.parse( String.format("(d | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | d | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_4 |" + "@AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_2 | @AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_4 | ~@AUX_%1$s_CC_2) & (c | @AUX_%1$s_CC_3 | @AUX_%1$s_CC_5) & (b | @AUX_%1$s_CC_3" + " | @AUX_%1$s_CC_5) & (b | c | @AUX_%1$s_CC_5) & (~@AUX_%1$s_CC_5 | @AUX_%1$s_CC_2) & ~@AUX_%1$s_CC_0", _c.f.name()))); diff --git a/src/test/java/com/booleworks/logicng/transformations/cnf/TseitinTest.java b/src/test/java/com/booleworks/logicng/transformations/cnf/TseitinTest.java index be3995c5..968b89a7 100644 --- a/src/test/java/com/booleworks/logicng/transformations/cnf/TseitinTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/cnf/TseitinTest.java @@ -81,9 +81,9 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { public void testNot(final FormulaContext _c) throws ParserException { final TseitinTransformation ts = new TseitinTransformation(_c.f, 0); - Assertions.assertThat(_c.p.parse("~a").transform(ts)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(ts)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").transform(ts)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~a").transform(ts)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(ts)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").transform(ts)).isEqualTo(_c.p.parse("a & ~b")); final Formula f1 = _c.p.parse("~(~(a | b) => ~(x | y))"); final Formula f2 = _c.p.parse("~(a <=> b)"); final Formula f3 = _c.p.parse("~(~(a | b) <=> ~(x | y))"); @@ -126,11 +126,11 @@ public void testFactorization(final FormulaContext _c) throws ParserException { public void testCC(final FormulaContext _c) throws ParserException { final TseitinTransformation ts = new TseitinTransformation(_c.f, 0); - Assertions.assertThat(_c.p.parse("a <=> (1 * b <= 1)").transform(ts)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(1 * b <= 1)").transform(ts)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").transform(ts)) + assertThat(_c.p.parse("a <=> (1 * b <= 1)").transform(ts)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(1 * b <= 1)").transform(ts)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("(1 * b + 1 * c + 1 * d <= 1)").transform(ts)) .isEqualTo(_c.p.parse("(~b | ~c) & (~b | ~d) & (~c | ~d)")); - Assertions.assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").transform(ts)).isEqualTo(_c.p.parse(String.format( + assertThat(_c.p.parse("~(1 * b + 1 * c + 1 * d <= 1)").transform(ts)).isEqualTo(_c.p.parse(String.format( "(d | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | @AUX_%1$s_CC_1 | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_3 | d | @AUX_%1$s_CC_4) & (~@AUX_%1$s_CC_4 | @AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_2 | @AUX_%1$s_CC_0) & (~@AUX_%1$s_CC_4 | ~@AUX_%1$s_CC_2) & (c | @AUX_%1$s_CC_3 | @AUX_%1$s_CC_5) & (b | @AUX_%1$s_CC_3 | @AUX_%1$s_CC_5) & (b | c | @AUX_%1$s_CC_5) & (~@AUX_%1$s_CC_5 | @AUX_%1$s_CC_2) & ~@AUX_%1$s_CC_0", _c.f.name()))); } diff --git a/src/test/java/com/booleworks/logicng/transformations/dnf/BDDDNFTest.java b/src/test/java/com/booleworks/logicng/transformations/dnf/BDDDNFTest.java index dad05e10..ac6599e8 100644 --- a/src/test/java/com/booleworks/logicng/transformations/dnf/BDDDNFTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/dnf/BDDDNFTest.java @@ -14,7 +14,6 @@ import com.booleworks.logicng.knowledgecompilation.bdds.jbuddy.BDDKernel; import com.booleworks.logicng.predicates.DNFPredicate; import com.booleworks.logicng.testutils.TestUtil; -import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -45,25 +44,25 @@ public void testBinaryOperators(final FormulaContext _c) { final BDDDNFTransformation bdddnf = new BDDDNFTransformation(_c.f); assertThat(_c.imp1.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp1, _c.imp1.transform(bdddnf), _c.imp1.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp1, _c.imp1.transform(bdddnf), _c.imp1.variables(_c.f))) .isTrue(); assertThat(_c.imp2.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp2, _c.imp2.transform(bdddnf), _c.imp2.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp2, _c.imp2.transform(bdddnf), _c.imp2.variables(_c.f))) .isTrue(); assertThat(_c.imp3.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.imp3, _c.imp3.transform(bdddnf), _c.imp3.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.imp3, _c.imp3.transform(bdddnf), _c.imp3.variables(_c.f))) .isTrue(); assertThat(_c.eq1.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq1, _c.eq1.transform(bdddnf), _c.eq1.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq1, _c.eq1.transform(bdddnf), _c.eq1.variables(_c.f))) .isTrue(); assertThat(_c.eq2.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq2, _c.eq2.transform(bdddnf), _c.eq2.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq2, _c.eq2.transform(bdddnf), _c.eq2.variables(_c.f))) .isTrue(); assertThat(_c.eq3.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq3, _c.eq3.transform(bdddnf), _c.eq3.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq3, _c.eq3.transform(bdddnf), _c.eq3.variables(_c.f))) .isTrue(); assertThat(_c.eq4.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(_c.eq4, _c.eq4.transform(bdddnf), _c.eq4.variables(_c.f))) + assertThat(TestUtil.equivalentModels(_c.eq4, _c.eq4.transform(bdddnf), _c.eq4.variables(_c.f))) .isTrue(); } @@ -79,11 +78,11 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -99,11 +98,11 @@ public void testNAryOperatorsWithExternalFactory(final FormulaContext _c) throws final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -119,11 +118,11 @@ public void testNAryOperatorsWithExternalFactory2(final FormulaContext _c) throw final Formula f2 = _c.p.parse("~(a & b) | c | ~(x | ~y)"); final Formula f3 = _c.p.parse("a | b | (~x & ~y)"); assertThat(f1.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(transformation), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(transformation), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(transformation).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(transformation), f3.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -132,26 +131,26 @@ public void testNot(final FormulaContext _c) throws ParserException { final DNFPredicate dnfPredicate = new DNFPredicate(_c.f); final BDDDNFTransformation bdddnf = new BDDDNFTransformation(_c.f); - Assertions.assertThat(_c.p.parse("~a").transform(bdddnf)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(bdddnf)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").transform(bdddnf)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~a").transform(bdddnf)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(bdddnf)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").transform(bdddnf)).isEqualTo(_c.p.parse("a & ~b")); final Formula f1 = _c.p.parse("~(~(a | b) => ~(x | y))"); final Formula f2 = _c.p.parse("~(a <=> b)"); final Formula f3 = _c.p.parse("~(~(a | b) <=> ~(x | y))"); final Formula f4 = _c.p.parse("~(a & b & ~x & ~y)"); final Formula f5 = _c.p.parse("~(a | b | ~x | ~y)"); assertThat(f1.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); assertThat(f4.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f4, f4.transform(bdddnf), f4.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f4, f4.transform(bdddnf), f4.variables(_c.f))).isTrue(); assertThat(f5.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f5, f5.transform(bdddnf), f5.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f5, f5.transform(bdddnf), f5.variables(_c.f))).isTrue(); assertThat(f5.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f5, f5.transform(bdddnf), f5.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f5, f5.transform(bdddnf), f5.variables(_c.f))).isTrue(); } @ParameterizedTest @@ -166,12 +165,12 @@ public void testCC(final FormulaContext _c) throws ParserException { final Formula f3 = p.parse("(1 * b + 1 * c + 1 * d <= 1)"); final Formula f4 = p.parse("~(1 * b + 1 * c + 1 * d <= 1)"); assertThat(f1.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f1, f1.transform(bdddnf), f1.variables(_c.f))).isTrue(); assertThat(f2.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f2, f2.transform(bdddnf), f2.variables(_c.f))).isTrue(); assertThat(f3.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f3, f3.transform(bdddnf), f3.variables(_c.f))).isTrue(); assertThat(f4.transform(bdddnf).holds(dnfPredicate)).isTrue(); - Assertions.assertThat(TestUtil.equivalentModels(f4, f4.transform(bdddnf), f4.variables(_c.f))).isTrue(); + assertThat(TestUtil.equivalentModels(f4, f4.transform(bdddnf), f4.variables(_c.f))).isTrue(); } } diff --git a/src/test/java/com/booleworks/logicng/transformations/dnf/DNFFactorizationTest.java b/src/test/java/com/booleworks/logicng/transformations/dnf/DNFFactorizationTest.java index 8a8b1543..e95e8a9c 100644 --- a/src/test/java/com/booleworks/logicng/transformations/dnf/DNFFactorizationTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/dnf/DNFFactorizationTest.java @@ -12,10 +12,10 @@ import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.events.FactorizationCreatedClauseEvent; -import com.booleworks.logicng.handlers.events.LogicNGEvent; +import com.booleworks.logicng.handlers.events.LNGEvent; import com.booleworks.logicng.io.parsers.ParserException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -65,22 +65,22 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { assertThat(_c.and1.transform(dnfFactorization)).isEqualTo(_c.and1); assertThat(_c.or1.transform(dnfFactorization)).isEqualTo(_c.or1); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("~a | ~b | c | (~x & y)")); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("(~a & ~b & c & ~x) | (~a & ~b & c & y)")); - Assertions.assertThat(_c.p.parse("a & b & (~x | ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("a & b & (~x | ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("(a & b & ~x) | (a & b & ~y)")); assertThat(_c.and1.transform(dnfFactorization).isDNF(_c.f)).isTrue(); assertThat(_c.or1.transform(dnfFactorization).isDNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(dnfFactorization).isDNF(_c.f)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(dnfFactorization).isDNF(_c.f)) .isTrue(); - Assertions.assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(dnfFactorization).isCNF(_c.f)) + assertThat(_c.p.parse("~(a | b) & c & ~(x & ~y) & (w => z)").transform(dnfFactorization).isCNF(_c.f)) .isFalse(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization).isDNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization).isCNF(_c.f)).isFalse(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(dnfFactorization).isDNF(_c.f)).isTrue(); - Assertions.assertThat(_c.p.parse("a | b | (~x & ~y)").transform(dnfFactorization).isCNF(_c.f)).isFalse(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization).isDNF(_c.f)).isTrue(); + assertThat(_c.p.parse("~(a & b) | c | ~(x | ~y)").transform(dnfFactorization).isCNF(_c.f)).isFalse(); + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(dnfFactorization).isDNF(_c.f)).isTrue(); + assertThat(_c.p.parse("a | b | (~x & ~y)").transform(dnfFactorization).isCNF(_c.f)).isFalse(); } @ParameterizedTest @@ -88,18 +88,18 @@ public void testNAryOperators(final FormulaContext _c) throws ParserException { public void testNot(final FormulaContext _c) throws ParserException { final DNFFactorization dnfFactorization = new DNFFactorization(_c.f); - Assertions.assertThat(_c.p.parse("~a").transform(dnfFactorization)).isEqualTo(_c.p.parse("~a")); - Assertions.assertThat(_c.p.parse("~~a").transform(dnfFactorization)).isEqualTo(_c.p.parse("a")); - Assertions.assertThat(_c.p.parse("~(a => b)").transform(dnfFactorization)).isEqualTo(_c.p.parse("a & ~b")); - Assertions.assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").transform(dnfFactorization)) + assertThat(_c.p.parse("~a").transform(dnfFactorization)).isEqualTo(_c.p.parse("~a")); + assertThat(_c.p.parse("~~a").transform(dnfFactorization)).isEqualTo(_c.p.parse("a")); + assertThat(_c.p.parse("~(a => b)").transform(dnfFactorization)).isEqualTo(_c.p.parse("a & ~b")); + assertThat(_c.p.parse("~(~(a | b) => ~(x | y))").transform(dnfFactorization)) .isEqualTo(_c.p.parse("(~a & ~b & x) | (~a & ~b & y)")); - Assertions.assertThat(_c.p.parse("~(a <=> b)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a <=> b)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("(~a & b) | (a & ~b)")); - Assertions.assertThat(_c.p.parse("~(a & b & ~x & ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a & b & ~x & ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("~a | ~b | x | y")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("~a & ~b & x & y")); - Assertions.assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(dnfFactorization)) + assertThat(_c.p.parse("~(a | b | ~x | ~y)").transform(dnfFactorization)) .isEqualTo(_c.p.parse("~a & ~b & x & y")); } @@ -123,12 +123,7 @@ public void testWithHandler(final FormulaContext _c) throws ParserException { private int clauses = 0; @Override - public boolean isAborted() { - return aborted; - } - - @Override - public boolean shouldResume(final LogicNGEvent event) { + public boolean shouldResume(final LNGEvent event) { if (event == FACTORIZATION_STARTED) { aborted = false; dists = 0; @@ -143,14 +138,14 @@ public boolean shouldResume(final LogicNGEvent event) { return !aborted; } }; - final DNFFactorization factorization = new DNFFactorization(_c.f, handler, null); - Formula dnf = factorization.apply(formula); - assertThat(handler.isAborted()).isTrue(); - assertThat(dnf).isNull(); + final DNFFactorization factorization = new DNFFactorization(_c.f, null); + LNGResult dnf = factorization.apply(formula, handler); + assertThat(dnf.isSuccess()).isFalse(); + assertThat(dnf.getResult()).isNull(); formula = _c.p.parse("~(a | b)"); - dnf = factorization.apply(formula); - assertThat(handler.isAborted()).isFalse(); - assertThat(dnf).isNotNull(); + dnf = factorization.apply(formula, handler); + assertThat(dnf.isSuccess()).isTrue(); + assertThat(dnf.getResult()).isNotNull(); } } diff --git a/src/test/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifierTest.java b/src/test/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifierTest.java index 7dfb4139..6b3944c0 100644 --- a/src/test/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifierTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/simplification/AdvancedSimplifierTest.java @@ -14,6 +14,7 @@ import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.handlers.BoundedOptimizationHandler; import com.booleworks.logicng.handlers.ComputationHandler; +import com.booleworks.logicng.handlers.LNGResult; import com.booleworks.logicng.handlers.TimeoutHandler; import com.booleworks.logicng.io.parsers.ParserException; import com.booleworks.logicng.io.readers.FormulaReader; @@ -98,7 +99,7 @@ public void testPrimeCompilerIsCancelled(final FormulaContext _c) throws ParserE @ParameterizedTest @MethodSource("contexts") - public void testzSmusComputationIsCancelled(final FormulaContext _c) throws ParserException { + public void testSmusComputationIsCancelled(final FormulaContext _c) throws ParserException { final ComputationHandler handler = new BoundedOptimizationHandler(-1, 5); final Formula formula = _c.f.parse("a&(b|c)"); testHandler(handler, formula, true); @@ -159,15 +160,13 @@ private void computeAndVerify(final Formula formula) { private void testHandler(final ComputationHandler handler, final Formula formula, final boolean expAborted) { final AdvancedSimplifier simplifierWithHandler = - new AdvancedSimplifier(formula.factory(), AdvancedSimplifierConfig.builder().build(), handler); - final Formula simplified = formula.transform(simplifierWithHandler); - assertThat(handler.isAborted()).isEqualTo(expAborted); + new AdvancedSimplifier(formula.factory(), AdvancedSimplifierConfig.builder().build()); + final LNGResult simplified = formula.transform(simplifierWithHandler, handler); + assertThat(simplified.isSuccess()).isEqualTo(!expAborted); if (expAborted) { - assertThat(handler.isAborted()).isTrue(); - assertThat(simplified).isNull(); + assertThat(simplified.getResult()).isNull(); } else { - assertThat(handler.isAborted()).isFalse(); - assertThat(simplified).isNotNull(); + assertThat(simplified.getResult()).isNotNull(); } } } diff --git a/src/test/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifierTest.java b/src/test/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifierTest.java index 9853185f..bd5cd6f6 100644 --- a/src/test/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifierTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/simplification/BackboneSimplifierTest.java @@ -4,6 +4,8 @@ package com.booleworks.logicng.transformations.simplification; +import static org.assertj.core.api.Assertions.assertThat; + import com.booleworks.logicng.formulas.FormulaContext; import com.booleworks.logicng.formulas.TestWithFormulaContext; import com.booleworks.logicng.io.parsers.ParserException; @@ -18,13 +20,13 @@ public class BackboneSimplifierTest extends TestWithFormulaContext { public void testTrivialBackbones(final FormulaContext _c) throws ParserException { final BackboneSimplifier backboneSimplifier = new BackboneSimplifier(_c.f); - Assertions.assertThat(_c.p.parse("$true").transform(backboneSimplifier)).isEqualTo(_c.p.parse("$true")); - Assertions.assertThat(_c.p.parse("$false").transform(backboneSimplifier)).isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A & (A => B) & ~B").transform(backboneSimplifier)) + assertThat(_c.p.parse("$true").transform(backboneSimplifier)).isEqualTo(_c.p.parse("$true")); + assertThat(_c.p.parse("$false").transform(backboneSimplifier)).isEqualTo(_c.p.parse("$false")); + assertThat(_c.p.parse("A & (A => B) & ~B").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("$false")); - Assertions.assertThat(_c.p.parse("A").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A")); - Assertions.assertThat(_c.p.parse("A & B").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A & B")); - Assertions.assertThat(_c.p.parse("A | B | C").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A | B | C")); + assertThat(_c.p.parse("A").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A")); + assertThat(_c.p.parse("A & B").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A & B")); + assertThat(_c.p.parse("A | B | C").transform(backboneSimplifier)).isEqualTo(_c.p.parse("A | B | C")); } @ParameterizedTest @@ -32,15 +34,15 @@ public void testTrivialBackbones(final FormulaContext _c) throws ParserException public void testRealBackbones(final FormulaContext _c) throws ParserException { final BackboneSimplifier backboneSimplifier = new BackboneSimplifier(_c.f); - Assertions.assertThat(_c.p.parse("A & B & (B | C)").transform(backboneSimplifier)) + assertThat(_c.p.parse("A & B & (B | C)").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("A & B")); - Assertions.assertThat(_c.p.parse("A & B & (~B | C)").transform(backboneSimplifier)) + assertThat(_c.p.parse("A & B & (~B | C)").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("A & B & C")); - Assertions.assertThat(_c.p.parse("A & B & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) + assertThat(_c.p.parse("A & B & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("A & B & C & F")); - Assertions.assertThat(_c.p.parse("X & Y & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) + assertThat(_c.p.parse("X & Y & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("X & Y & (~B | C) & (B | D) & (A => F)")); - Assertions.assertThat(_c.p.parse("~A & ~B & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) + assertThat(_c.p.parse("~A & ~B & (~B | C) & (B | D) & (A => F)").transform(backboneSimplifier)) .isEqualTo(_c.p.parse("~A & ~B & D")); } } diff --git a/src/test/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifierTest.java b/src/test/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifierTest.java index 623ba8e0..aff44a05 100644 --- a/src/test/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifierTest.java +++ b/src/test/java/com/booleworks/logicng/transformations/simplification/DistributiveSimplifierTest.java @@ -57,8 +57,8 @@ public void testPropagations(final FormulaContext _c) throws ParserException { assertThat(_c.f.or(_c.and1, _c.a).transform(distributiveSimplifier)).isEqualTo(_c.f.or(_c.and1, _c.a)); assertThat(_c.f.or(_c.and2, _c.a).transform(distributiveSimplifier)).isEqualTo(_c.f.or(_c.and2, _c.a)); assertThat(_c.f.or(_c.or1, _c.x).transform(distributiveSimplifier)).isEqualTo(_c.or1); - Assertions.assertThat(_c.p.parse( - "(a | b | ~c) & (~a | ~d) & (~c | d) & (~b | e | ~f | g) & (e | f | g | h) & (e | ~f | ~g | h) & f & c") + assertThat(_c.p.parse( + "(a | b | ~c) & (~a | ~d) & (~c | d) & (~b | e | ~f | g) & (e | f | g | h) & (e | ~f | ~g | h) & f & c") .transform(distributiveSimplifier)) .isEqualTo(_c.p.parse( "(a | b | ~c) & (~a | ~d) & (~c | d) & f & c & (e | (~b | ~f | g) & (f | g | h) & (~f | ~g | h))")); diff --git a/src/test/java/com/booleworks/logicng/util/CollectionHelperTest.java b/src/test/java/com/booleworks/logicng/util/CollectionHelperTest.java index 9caf5d49..9e8dc0f5 100644 --- a/src/test/java/com/booleworks/logicng/util/CollectionHelperTest.java +++ b/src/test/java/com/booleworks/logicng/util/CollectionHelperTest.java @@ -20,25 +20,25 @@ public class CollectionHelperTest { @Test public void testNullOrEmpty() { - Assertions.assertThat(CollectionHelper.nullOrEmpty(null)).isTrue(); - Assertions.assertThat(CollectionHelper.nullOrEmpty(Collections.emptySet())).isTrue(); - Assertions.assertThat(CollectionHelper.nullOrEmpty(Collections.emptyMap().entrySet())).isTrue(); - Assertions.assertThat(CollectionHelper.nullOrEmpty(Collections.singletonList(2))).isFalse(); + assertThat(CollectionHelper.nullOrEmpty(null)).isTrue(); + assertThat(CollectionHelper.nullOrEmpty(Collections.emptySet())).isTrue(); + assertThat(CollectionHelper.nullOrEmpty(Collections.emptyMap().entrySet())).isTrue(); + assertThat(CollectionHelper.nullOrEmpty(Collections.singletonList(2))).isFalse(); } @Test public void testNullSafe() { - Assertions.assertThat(CollectionHelper.nullSafe(null)).isEmpty(); + assertThat(CollectionHelper.nullSafe(null)).isEmpty(); final List strings = Arrays.asList("a", "b", "c"); - Assertions.assertThat(CollectionHelper.nullSafe(strings)).isEqualTo(strings); + assertThat(CollectionHelper.nullSafe(strings)).isEqualTo(strings); - Assertions.assertThat(CollectionHelper.nullSafe(() -> Arrays.asList("a", "b"), ArrayList::new)) + assertThat(CollectionHelper.nullSafe(() -> Arrays.asList("a", "b"), ArrayList::new)) .isEqualTo(new ArrayList<>(Arrays.asList("a", "b"))); - Assertions.assertThat(CollectionHelper.nullSafe(() -> new TreeSet<>(Arrays.asList("a", "b")), TreeSet::new)) + assertThat(CollectionHelper.nullSafe(() -> new TreeSet<>(Arrays.asList("a", "b")), TreeSet::new)) .isEqualTo(new TreeSet<>(Arrays.asList("a", "b"))); - Assertions.assertThat(CollectionHelper.nullSafe(() -> (ArrayList) null, ArrayList::new)) + assertThat(CollectionHelper.nullSafe(() -> (ArrayList) null, ArrayList::new)) .isEqualTo(new ArrayList()); - Assertions.assertThat(CollectionHelper.nullSafe(() -> (TreeSet) null, TreeSet::new)) + assertThat(CollectionHelper.nullSafe(() -> (TreeSet) null, TreeSet::new)) .isEqualTo(new TreeSet()); } diff --git a/src/test/java/com/booleworks/logicng/util/FormulaHelperTest.java b/src/test/java/com/booleworks/logicng/util/FormulaHelperTest.java index bf6fb1d3..acf27179 100644 --- a/src/test/java/com/booleworks/logicng/util/FormulaHelperTest.java +++ b/src/test/java/com/booleworks/logicng/util/FormulaHelperTest.java @@ -27,51 +27,51 @@ public class FormulaHelperTest extends TestWithFormulaContext { @ParameterizedTest @MethodSource("contexts") public void testVariables(final FormulaContext _c) { - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.verum)).isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.falsum)).isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.a)) + assertThat(FormulaHelper.variables(_c.f, _c.verum)).isEqualTo(new TreeSet<>()); + assertThat(FormulaHelper.variables(_c.f, _c.falsum)).isEqualTo(new TreeSet<>()); + assertThat(FormulaHelper.variables(_c.f, _c.a)) .isEqualTo(new TreeSet<>(Collections.singletonList(_c.a))); - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.na)) + assertThat(FormulaHelper.variables(_c.f, _c.na)) .isEqualTo(new TreeSet<>(Collections.singletonList(_c.a))); - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.imp1, _c.imp2, _c.imp3)) + assertThat(FormulaHelper.variables(_c.f, _c.imp1, _c.imp2, _c.imp3)) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.x, _c.y))); - Assertions.assertThat(FormulaHelper.variables(_c.f, _c.imp1, _c.y)) + assertThat(FormulaHelper.variables(_c.f, _c.imp1, _c.y)) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.y))); - Assertions.assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.verum, _c.falsum))) + assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.verum, _c.falsum))) .isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.imp1, _c.imp2, _c.imp3))) + assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.imp1, _c.imp2, _c.imp3))) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.x, _c.y))); - Assertions.assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.imp1, _c.y))) + assertThat(FormulaHelper.variables(_c.f, Arrays.asList(_c.imp1, _c.y))) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.y))); } @ParameterizedTest @MethodSource("contexts") public void testLiterals(final FormulaContext _c) { - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.verum)).isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.falsum)).isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.a)) + assertThat(FormulaHelper.literals(_c.f, _c.verum)).isEqualTo(new TreeSet<>()); + assertThat(FormulaHelper.literals(_c.f, _c.falsum)).isEqualTo(new TreeSet<>()); + assertThat(FormulaHelper.literals(_c.f, _c.a)) .isEqualTo(new TreeSet<>(Collections.singletonList(_c.a))); - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.na)) + assertThat(FormulaHelper.literals(_c.f, _c.na)) .isEqualTo(new TreeSet<>(Collections.singletonList(_c.na))); - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.imp1, _c.imp2, _c.imp3)) + assertThat(FormulaHelper.literals(_c.f, _c.imp1, _c.imp2, _c.imp3)) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.x, _c.y, _c.na, _c.nb))); - Assertions.assertThat(FormulaHelper.literals(_c.f, _c.imp1, _c.ny)) + assertThat(FormulaHelper.literals(_c.f, _c.imp1, _c.ny)) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.ny))); - Assertions.assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.verum, _c.falsum))) + assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.verum, _c.falsum))) .isEqualTo(new TreeSet<>()); - Assertions.assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.imp1, _c.imp2, _c.imp3))) + assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.imp1, _c.imp2, _c.imp3))) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.x, _c.y, _c.na, _c.nb))); - Assertions.assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.imp1, _c.ny))) + assertThat(FormulaHelper.literals(_c.f, Arrays.asList(_c.imp1, _c.ny))) .isEqualTo(new TreeSet<>(Arrays.asList(_c.a, _c.b, _c.ny))); } @ParameterizedTest @MethodSource("contexts") public void testNegateLiterals(final FormulaContext _c) { - Assertions.assertThat( + assertThat( (ArrayList) FormulaHelper.negateLiterals(_c.f, Collections.emptyList(), ArrayList::new)) .isEqualTo(new ArrayList()); assertThat((ArrayList) FormulaHelper.negateLiterals(_c.f, Arrays.asList(_c.a, _c.nb), ArrayList::new)) @@ -105,37 +105,37 @@ public void testNegate(final FormulaContext _c) { @ParameterizedTest @MethodSource("contexts") public void testSplitTopLevelAnd(final FormulaContext _c) { - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.verum)).isEqualTo(Collections.singletonList(_c.verum)); - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.falsum)) + assertThat(FormulaHelper.splitTopLevelAnd(_c.verum)).isEqualTo(Collections.singletonList(_c.verum)); + assertThat(FormulaHelper.splitTopLevelAnd(_c.falsum)) .isEqualTo(Collections.singletonList(_c.falsum)); - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.or1)).isEqualTo(Collections.singletonList(_c.or1)); - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.imp1)).isEqualTo(Collections.singletonList(_c.imp1)); + assertThat(FormulaHelper.splitTopLevelAnd(_c.or1)).isEqualTo(Collections.singletonList(_c.or1)); + assertThat(FormulaHelper.splitTopLevelAnd(_c.imp1)).isEqualTo(Collections.singletonList(_c.imp1)); - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.and1)).isEqualTo(Arrays.asList(_c.a, _c.b)); - Assertions.assertThat(FormulaHelper.splitTopLevelAnd(_c.and3)).isEqualTo(Arrays.asList(_c.or1, _c.or2)); + assertThat(FormulaHelper.splitTopLevelAnd(_c.and1)).isEqualTo(Arrays.asList(_c.a, _c.b)); + assertThat(FormulaHelper.splitTopLevelAnd(_c.and3)).isEqualTo(Arrays.asList(_c.or1, _c.or2)); } @ParameterizedTest @MethodSource("contexts") public void testStrings2Vars(final FormulaContext _c) { - Assertions.assertThat(FormulaHelper.strings2vars(_c.f, null)).isEmpty(); - Assertions.assertThat(FormulaHelper.strings2vars(_c.f, new TreeSet<>())).isEmpty(); - Assertions.assertThat(FormulaHelper.strings2vars(_c.f, Arrays.asList("a", "b", "c"))) + assertThat(FormulaHelper.strings2vars(_c.f, null)).isEmpty(); + assertThat(FormulaHelper.strings2vars(_c.f, new TreeSet<>())).isEmpty(); + assertThat(FormulaHelper.strings2vars(_c.f, Arrays.asList("a", "b", "c"))) .containsExactly(_c.a, _c.b, _c.c); - Assertions.assertThat(FormulaHelper.strings2vars(_c.f, Arrays.asList("a", "b", "c", "a", "a"))) + assertThat(FormulaHelper.strings2vars(_c.f, Arrays.asList("a", "b", "c", "a", "a"))) .containsExactly(_c.a, _c.b, _c.c); } @ParameterizedTest @MethodSource("contexts") public void testStrings2Literals(final FormulaContext _c) { - Assertions.assertThat(FormulaHelper.strings2literals(_c.f, null, "~")).isEmpty(); - Assertions.assertThat(FormulaHelper.strings2literals(_c.f, new TreeSet<>(), "~")).isEmpty(); - Assertions.assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("a", "~b", "c"), "~")) + assertThat(FormulaHelper.strings2literals(_c.f, null, "~")).isEmpty(); + assertThat(FormulaHelper.strings2literals(_c.f, new TreeSet<>(), "~")).isEmpty(); + assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("a", "~b", "c"), "~")) .containsExactly(_c.a, _c.nb, _c.c); - Assertions.assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("~a", "b", "c", "a", "a"), "~")) + assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("~a", "b", "c", "a", "a"), "~")) .containsExactly(_c.a, _c.na, _c.b, _c.c); - Assertions.assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("-a", "b", "c", "a", "a"), "-")) + assertThat(FormulaHelper.strings2literals(_c.f, Arrays.asList("-a", "b", "c", "a", "a"), "-")) .containsExactly(_c.a, _c.na, _c.b, _c.c); } diff --git a/src/test/java/com/booleworks/logicng/util/FormulaRandomizerTest.java b/src/test/java/com/booleworks/logicng/util/FormulaRandomizerTest.java index 785bb17f..5c98940c 100644 --- a/src/test/java/com/booleworks/logicng/util/FormulaRandomizerTest.java +++ b/src/test/java/com/booleworks/logicng/util/FormulaRandomizerTest.java @@ -20,7 +20,6 @@ import com.booleworks.logicng.formulas.PBConstraint; import com.booleworks.logicng.formulas.Variable; import com.booleworks.logicng.functions.FormulaDepthFunction; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -40,11 +39,11 @@ public class FormulaRandomizerTest { public void testDeterminism() { final Formula expected = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()).formula(3); - Assertions.assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()).formula(3)) + assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()).formula(3)) .isEqualTo(expected); - Assertions.assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(43).build()).formula(3)) + assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(43).build()).formula(3)) .isNotEqualTo(expected); - Assertions.assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().build()).formula(3)) + assertThat(new FormulaRandomizer(f, FormulaRandomizerConfig.builder().build()).formula(3)) .isNotEqualTo(expected); final List expectedList = randomFormulas(); for (int i = 0; i < 10; i++) { @@ -105,7 +104,7 @@ public void testVariable() { .weightExo(1) .seed(42).build()); for (int i = 0; i < 100; i++) { - Assertions.assertThat(random2.formula(4).variables(f)).isSubsetOf(vars2); + assertThat(random2.formula(4).variables(f)).isSubsetOf(vars2); } } @@ -168,7 +167,7 @@ public void testAtom() { final FormulaRandomizer randomOnlyLiterals = new FormulaRandomizer(f, FormulaRandomizerConfig.builder() .weightConstant(0).weightPositiveLiteral(3).weightNegativeLiteral(6).seed(42).build()); for (int i = 0; i < 100; i++) { - Assertions.assertThat(randomOnlyLiterals.atom().type()).isEqualTo(FType.LITERAL); + assertThat(randomOnlyLiterals.atom().type()).isEqualTo(FType.LITERAL); } } @@ -176,13 +175,13 @@ public void testAtom() { public void testAnd() { final FormulaRandomizer random = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()); for (int i = 0; i < 10; i++) { - Assertions.assertThat(random.and(0).isAtomicFormula()).isTrue(); + assertThat(random.and(0).isAtomicFormula()).isTrue(); } for (int depth = 1; depth <= 7; depth++) { for (int i = 0; i < 10; i++) { final Formula formula = random.and(depth); assertThat(formula).isInstanceOf(And.class); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); } } } @@ -191,13 +190,13 @@ public void testAnd() { public void testOr() { final FormulaRandomizer random = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()); for (int i = 0; i < 10; i++) { - Assertions.assertThat(random.or(0).isAtomicFormula()).isTrue(); + assertThat(random.or(0).isAtomicFormula()).isTrue(); } for (int depth = 1; depth <= 7; depth++) { for (int i = 0; i < 10; i++) { final Formula formula = random.or(depth); assertThat(formula).isInstanceOf(Or.class); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); } } } @@ -206,14 +205,14 @@ public void testOr() { public void testNot() { final FormulaRandomizer random = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()); for (int i = 0; i < 10; i++) { - Assertions.assertThat(random.not(0).isAtomicFormula()).isTrue(); - Assertions.assertThat(random.not(1).isAtomicFormula()).isTrue(); + assertThat(random.not(0).isAtomicFormula()).isTrue(); + assertThat(random.not(1).isAtomicFormula()).isTrue(); } for (int depth = 2; depth <= 7; depth++) { for (int i = 0; i < 10; i++) { final Formula formula = random.not(depth); assertThat(formula).isInstanceOf(Not.class); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); } } } @@ -222,13 +221,13 @@ public void testNot() { public void testImpl() { final FormulaRandomizer random = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()); for (int i = 0; i < 10; i++) { - Assertions.assertThat(random.impl(0).isAtomicFormula()).isTrue(); + assertThat(random.impl(0).isAtomicFormula()).isTrue(); } for (int depth = 1; depth <= 7; depth++) { for (int i = 0; i < 10; i++) { final Formula formula = random.impl(depth); assertThat(formula).isInstanceOf(Implication.class); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); } } } @@ -237,13 +236,13 @@ public void testImpl() { public void testEquiv() { final FormulaRandomizer random = new FormulaRandomizer(f, FormulaRandomizerConfig.builder().seed(42).build()); for (int i = 0; i < 10; i++) { - Assertions.assertThat(random.equiv(0).isAtomicFormula()).isTrue(); + assertThat(random.equiv(0).isAtomicFormula()).isTrue(); } for (int depth = 1; depth <= 7; depth++) { for (int i = 0; i < 10; i++) { final Formula formula = random.equiv(depth); assertThat(formula).isInstanceOf(Equivalence.class); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(depth); } } } @@ -418,7 +417,7 @@ public void testFormula() { for (int i = 0; i < 10000; i++) { final Formula formula = random.formula(3); countOccurrences(formula, occurrences, 3); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(3); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(3); } final int totalOccurrences = occurrences.get("and") + occurrences.get("or") + occurrences.get("impl") + occurrences.get("equiv"); @@ -453,7 +452,7 @@ public void testFormulaWithPbcs() { for (int i = 0; i < 10000; i++) { final Formula formula = random.formula(3); countOccurrences(formula, occurrences, 3); - Assertions.assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(3); + assertThat(formula.apply(new FormulaDepthFunction(f))).isLessThanOrEqualTo(3); } assertThat(occurrences.get("negLit")).isStrictlyBetween((int) (.8 * occurrences.get("posLit")), (int) (1.2 * occurrences.get("posLit")));