repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3Formula.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.errorprone.annotations.Immutable;
import com.microsoft.z3.Native;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.EnumerationFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingModeFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.StringFormula;
@Immutable
abstract class Z3Formula implements Formula {
private final long z3expr;
private final long z3context;
private final int hashCache;
private Z3Formula(long z3context, long z3expr) {
checkArgument(z3context != 0, "Z3 context is null");
checkArgument(z3expr != 0, "Z3 formula is null");
this.z3expr = z3expr;
this.z3context = z3context;
Native.incRef(z3context, z3expr);
this.hashCache = Native.getAstHash(z3context, z3expr);
}
@Override
public final String toString() {
return Native.astToString(z3context, z3expr);
}
@Override
public final boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Z3Formula)) {
return false;
}
Z3Formula other = (Z3Formula) obj;
return (z3context == other.z3context) && Native.isEqAst(z3context, z3expr, other.z3expr);
}
@Override
public final int hashCode() {
return hashCache;
}
final long getFormulaInfo() {
return z3expr;
}
@SuppressWarnings("ClassTypeParameterName")
static final class Z3ArrayFormula<TI extends Formula, TE extends Formula> extends Z3Formula
implements ArrayFormula<TI, TE> {
private final FormulaType<TI> indexType;
private final FormulaType<TE> elementType;
Z3ArrayFormula(
long pZ3context, long pZ3expr, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) {
super(pZ3context, pZ3expr);
indexType = pIndexType;
elementType = pElementType;
}
public FormulaType<TI> getIndexType() {
return indexType;
}
public FormulaType<TE> getElementType() {
return elementType;
}
}
@Immutable
static final class Z3BitvectorFormula extends Z3Formula implements BitvectorFormula {
Z3BitvectorFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3FloatingPointFormula extends Z3Formula implements FloatingPointFormula {
Z3FloatingPointFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3FloatingPointRoundingModeFormula extends Z3Formula
implements FloatingPointRoundingModeFormula {
Z3FloatingPointRoundingModeFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3IntegerFormula extends Z3Formula implements IntegerFormula {
Z3IntegerFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3RationalFormula extends Z3Formula implements RationalFormula {
Z3RationalFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3BooleanFormula extends Z3Formula implements BooleanFormula {
Z3BooleanFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3StringFormula extends Z3Formula implements StringFormula {
Z3StringFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3RegexFormula extends Z3Formula implements RegexFormula {
Z3RegexFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
@Immutable
static final class Z3EnumerationFormula extends Z3Formula implements EnumerationFormula {
Z3EnumerationFormula(long z3context, long z3expr) {
super(z3context, z3expr);
}
}
}
| 4,629 | 27.231707 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3FormulaCreator.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Table;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.Z3Exception;
import com.microsoft.z3.enumerations.Z3_ast_kind;
import com.microsoft.z3.enumerations.Z3_decl_kind;
import com.microsoft.z3.enumerations.Z3_sort_kind;
import com.microsoft.z3.enumerations.Z3_symbol_kind;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.common.time.Timer;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.EnumerationFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.basicimpl.FormulaCreator;
import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3ArrayFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BitvectorFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BooleanFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3EnumerationFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointRoundingModeFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3IntegerFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RationalFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RegexFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3StringFormula;
@Options(prefix = "solver.z3")
class Z3FormulaCreator extends FormulaCreator<Long, Long, Long, Long> {
private static final ImmutableMap<Integer, Object> Z3_CONSTANTS =
ImmutableMap.<Integer, Object>builder()
.put(Z3_decl_kind.Z3_OP_TRUE.toInt(), true)
.put(Z3_decl_kind.Z3_OP_FALSE.toInt(), false)
.put(Z3_decl_kind.Z3_OP_FPA_PLUS_ZERO.toInt(), +0.0)
.put(Z3_decl_kind.Z3_OP_FPA_MINUS_ZERO.toInt(), -0.0)
.put(Z3_decl_kind.Z3_OP_FPA_PLUS_INF.toInt(), Double.POSITIVE_INFINITY)
.put(Z3_decl_kind.Z3_OP_FPA_MINUS_INF.toInt(), Double.NEGATIVE_INFINITY)
.put(Z3_decl_kind.Z3_OP_FPA_NAN.toInt(), Double.NaN)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN.toInt(),
FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY.toInt(),
FloatingPointRoundingMode.NEAREST_TIES_AWAY)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_POSITIVE.toInt(),
FloatingPointRoundingMode.TOWARD_POSITIVE)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_NEGATIVE.toInt(),
FloatingPointRoundingMode.TOWARD_NEGATIVE)
.put(Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_ZERO.toInt(), FloatingPointRoundingMode.TOWARD_ZERO)
.buildOrThrow();
// Set of error messages that might occur if Z3 is interrupted.
private static final ImmutableSet<String> Z3_INTERRUPT_ERRORS =
ImmutableSet.of(
"canceled", // Z3::src/util/common_msgs.cpp
"push canceled", // src/smt/smt_context.cpp
"interrupted from keyboard", // Z3: src/solver/check_sat_result.cpp
"Proof error!",
"interrupted", // Z3::src/solver/check_sat_result.cpp
"maximization suspended" // Z3::src/opt/opt_solver.cpp
);
@Option(secure = true, description = "Whether to use PhantomReferences for discarding Z3 AST")
private boolean usePhantomReferences = false;
/**
* We need to track all created symbols for parsing.
*
* <p>This map stores symbols (names) and their declaration (type information).
*/
private final Map<String, Long> symbolsToDeclarations = new LinkedHashMap<>();
private final Table<Long, Long, Long> allocatedArraySorts = HashBasedTable.create();
/** Automatic clean-up of Z3 ASTs. */
private final ReferenceQueue<Z3Formula> referenceQueue = new ReferenceQueue<>();
private final IdentityHashMap<PhantomReference<? extends Z3Formula>, Long> referenceMap =
new IdentityHashMap<>();
// todo: getters for statistic.
private final Timer cleanupTimer = new Timer();
protected final ShutdownNotifier shutdownNotifier;
@SuppressWarnings("ParameterNumber")
Z3FormulaCreator(
long pEnv,
long pBoolType,
long pIntegerType,
long pRealType,
long pStringType,
long pRegexType,
Configuration config,
ShutdownNotifier pShutdownNotifier)
throws InvalidConfigurationException {
super(pEnv, pBoolType, pIntegerType, pRealType, pStringType, pRegexType);
shutdownNotifier = pShutdownNotifier;
config.inject(this);
}
final Z3Exception handleZ3Exception(Z3Exception e) throws Z3Exception, InterruptedException {
if (Z3_INTERRUPT_ERRORS.contains(e.getMessage())) {
shutdownNotifier.shutdownIfNecessary();
}
throw e;
}
@Override
public Long makeVariable(Long type, String varName) {
long z3context = getEnv();
long symbol = Native.mkStringSymbol(z3context, varName);
long var = Native.mkConst(z3context, symbol, type);
Native.incRef(z3context, var);
symbolsToDeclarations.put(varName, Native.getAppDecl(z3context, var));
return var;
}
@Override
public Long extractInfo(Formula pT) {
if (pT instanceof Z3Formula) {
return ((Z3Formula) pT).getFormulaInfo();
}
throw new IllegalArgumentException(
"Cannot get the formula info of type " + pT.getClass().getSimpleName() + " in the Solver!");
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) {
Long term = extractInfo(pFormula);
return (FormulaType<T>) getFormulaType(term);
}
public FormulaType<?> getFormulaTypeFromSort(Long pSort) {
long z3context = getEnv();
Z3_sort_kind sortKind = Z3_sort_kind.fromInt(Native.getSortKind(z3context, pSort));
switch (sortKind) {
case Z3_BOOL_SORT:
return FormulaType.BooleanType;
case Z3_INT_SORT:
return FormulaType.IntegerType;
case Z3_REAL_SORT:
return FormulaType.RationalType;
case Z3_BV_SORT:
return FormulaType.getBitvectorTypeWithSize(Native.getBvSortSize(z3context, pSort));
case Z3_ARRAY_SORT:
long domainSort = Native.getArraySortDomain(z3context, pSort);
long rangeSort = Native.getArraySortRange(z3context, pSort);
return FormulaType.getArrayType(
getFormulaTypeFromSort(domainSort), getFormulaTypeFromSort(rangeSort));
case Z3_FLOATING_POINT_SORT:
return FormulaType.getFloatingPointType(
Native.fpaGetEbits(z3context, pSort), Native.fpaGetSbits(z3context, pSort) - 1);
case Z3_ROUNDING_MODE_SORT:
return FormulaType.FloatingPointRoundingModeType;
case Z3_RE_SORT:
return FormulaType.RegexType;
case Z3_DATATYPE_SORT:
int n = Native.getDatatypeSortNumConstructors(z3context, pSort);
ImmutableSet.Builder<String> elements = ImmutableSet.builder();
for (int i = 0; i < n; i++) {
long decl = Native.getDatatypeSortConstructor(z3context, pSort, i);
elements.add(symbolToString(Native.getDeclName(z3context, decl)));
}
return FormulaType.getEnumerationType(
Native.sortToString(z3context, pSort), elements.build());
case Z3_RELATION_SORT:
case Z3_FINITE_DOMAIN_SORT:
case Z3_SEQ_SORT:
case Z3_UNKNOWN_SORT:
case Z3_UNINTERPRETED_SORT:
if (Native.isStringSort(z3context, pSort)) {
return FormulaType.StringType;
} else {
// TODO: support for remaining sorts.
throw new IllegalArgumentException(
"Unknown formula type "
+ Native.sortToString(z3context, pSort)
+ " with sort "
+ sortKind);
}
default:
throw new UnsupportedOperationException("Unexpected state.");
}
}
@Override
public FormulaType<?> getFormulaType(Long pFormula) {
long sort = Native.getSort(getEnv(), pFormula);
return getFormulaTypeFromSort(sort);
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType(
ArrayFormula<TD, TR> pArray) {
return ((Z3ArrayFormula<TD, TR>) pArray).getElementType();
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType(
ArrayFormula<TD, TR> pArray) {
return ((Z3ArrayFormula<TD, TR>) pArray).getIndexType();
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> ArrayFormula<TD, TR> encapsulateArray(
Long pTerm, FormulaType<TD> pIndexType, FormulaType<TR> pElementType) {
assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType));
cleanupReferences();
return storePhantomReference(
new Z3ArrayFormula<>(getEnv(), pTerm, pIndexType, pElementType), pTerm);
}
private <T extends Z3Formula> T storePhantomReference(T out, Long pTerm) {
if (usePhantomReferences) {
PhantomReference<T> ref = new PhantomReference<>(out, referenceQueue);
referenceMap.put(ref, pTerm);
}
return out;
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> T encapsulate(FormulaType<T> pType, Long pTerm) {
assert pType.equals(getFormulaType(pTerm))
|| (pType.equals(FormulaType.RationalType)
&& getFormulaType(pTerm).equals(FormulaType.IntegerType))
: String.format(
"Trying to encapsulate formula of type %s as %s", getFormulaType(pTerm), pType);
cleanupReferences();
if (pType.isBooleanType()) {
return (T) storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
} else if (pType.isIntegerType()) {
return (T) storePhantomReference(new Z3IntegerFormula(getEnv(), pTerm), pTerm);
} else if (pType.isRationalType()) {
return (T) storePhantomReference(new Z3RationalFormula(getEnv(), pTerm), pTerm);
} else if (pType.isStringType()) {
return (T) storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
} else if (pType.isRegexType()) {
return (T) storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
} else if (pType.isBitvectorType()) {
return (T) storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
} else if (pType.isFloatingPointType()) {
return (T) storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
} else if (pType.isFloatingPointRoundingModeType()) {
return (T)
storePhantomReference(new Z3FloatingPointRoundingModeFormula(getEnv(), pTerm), pTerm);
} else if (pType.isArrayType()) {
ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType;
return (T)
storePhantomReference(
new Z3ArrayFormula<>(getEnv(), pTerm, arrFt.getIndexType(), arrFt.getElementType()),
pTerm);
} else if (pType.isEnumerationType()) {
return (T) storePhantomReference(new Z3EnumerationFormula(getEnv(), pTerm), pTerm);
}
throw new IllegalArgumentException("Cannot create formulas of type " + pType + " in Z3");
}
@Override
public BooleanFormula encapsulateBoolean(Long pTerm) {
assert getFormulaType(pTerm).isBooleanType();
cleanupReferences();
return storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
}
@Override
public BitvectorFormula encapsulateBitvector(Long pTerm) {
assert getFormulaType(pTerm).isBitvectorType();
cleanupReferences();
return storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
}
@Override
protected FloatingPointFormula encapsulateFloatingPoint(Long pTerm) {
assert getFormulaType(pTerm).isFloatingPointType();
cleanupReferences();
return storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
}
@Override
protected StringFormula encapsulateString(Long pTerm) {
assert getFormulaType(pTerm).isStringType()
: String.format(
"Term %s has unexpected type %s.",
Native.astToString(getEnv(), pTerm),
Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
cleanupReferences();
return storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
}
@Override
protected RegexFormula encapsulateRegex(Long pTerm) {
assert getFormulaType(pTerm).isRegexType()
: String.format(
"Term %s has unexpected type %s.",
Native.astToString(getEnv(), pTerm),
Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
cleanupReferences();
return storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
}
@Override
protected EnumerationFormula encapsulateEnumeration(Long pTerm) {
assert getFormulaType(pTerm).isEnumerationType()
: String.format(
"Term %s has unexpected type %s.",
Native.astToString(getEnv(), pTerm),
Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
cleanupReferences();
return storePhantomReference(new Z3EnumerationFormula(getEnv(), pTerm), pTerm);
}
@Override
public Long getArrayType(Long pIndexType, Long pElementType) {
Long allocatedArraySort = allocatedArraySorts.get(pIndexType, pElementType);
if (allocatedArraySort == null) {
allocatedArraySort = Native.mkArraySort(getEnv(), pIndexType, pElementType);
Native.incRef(getEnv(), allocatedArraySort);
allocatedArraySorts.put(pIndexType, pElementType, allocatedArraySort);
}
return allocatedArraySort;
}
@Override
public Long getBitvectorType(int pBitwidth) {
checkArgument(pBitwidth > 0, "Cannot use bitvector type with size %s", pBitwidth);
long bvSort = Native.mkBvSort(getEnv(), pBitwidth);
Native.incRef(getEnv(), Native.sortToAst(getEnv(), bvSort));
return bvSort;
}
@Override
public Long getFloatingPointType(FormulaType.FloatingPointType type) {
long fpSort = Native.mkFpaSort(getEnv(), type.getExponentSize(), type.getMantissaSize() + 1);
Native.incRef(getEnv(), Native.sortToAst(getEnv(), fpSort));
return fpSort;
}
private void cleanupReferences() {
if (!usePhantomReferences) {
return;
}
cleanupTimer.start();
try {
Reference<? extends Z3Formula> ref;
while ((ref = referenceQueue.poll()) != null) {
long z3ast = referenceMap.remove(ref);
Native.decRef(environment, z3ast);
}
} finally {
cleanupTimer.stop();
}
}
private String getAppName(long f) {
long funcDecl = Native.getAppDecl(environment, f);
long symbol = Native.getDeclName(environment, funcDecl);
return symbolToString(symbol);
}
@Override
public <R> R visit(FormulaVisitor<R> visitor, final Formula formula, final Long f) {
switch (Z3_ast_kind.fromInt(Native.getAstKind(environment, f))) {
case Z3_NUMERAL_AST:
return visitor.visitConstant(formula, convertValue(f));
case Z3_APP_AST:
int arity = Native.getAppNumArgs(environment, f);
int declKind = Native.getDeclKind(environment, Native.getAppDecl(environment, f));
if (arity == 0) {
// constants
Object value = Z3_CONSTANTS.get(declKind);
if (value != null) {
return visitor.visitConstant(formula, value);
// Rounding mode
} else if (declKind == Z3_decl_kind.Z3_OP_FPA_NUM.toInt()
|| Native.getSortKind(environment, Native.getSort(environment, f))
== Z3_sort_kind.Z3_ROUNDING_MODE_SORT.toInt()) {
return visitor.visitConstant(formula, convertValue(f));
// string constant
} else if (declKind == Z3_decl_kind.Z3_OP_INTERNAL.toInt()
&& Native.getSortKind(environment, Native.getSort(environment, f))
== Z3_sort_kind.Z3_SEQ_SORT.toInt()) {
return visitor.visitConstant(formula, convertValue(f));
// Free variable
} else if (declKind == Z3_decl_kind.Z3_OP_UNINTERPRETED.toInt()
|| declKind == Z3_decl_kind.Z3_OP_INTERNAL.toInt()) {
return visitor.visitFreeVariable(formula, getAppName(f));
// enumeration constant
} else if (declKind == Z3_decl_kind.Z3_OP_DT_CONSTRUCTOR.toInt()) {
return visitor.visitConstant(formula, convertValue(f));
} // else: fall-through with a function application
}
// Function application with zero or more parameters
ImmutableList.Builder<Formula> args = ImmutableList.builder();
ImmutableList.Builder<FormulaType<?>> argTypes = ImmutableList.builder();
for (int i = 0; i < arity; i++) {
long arg = Native.getAppArg(environment, f, i);
FormulaType<?> argumentType = getFormulaType(arg);
args.add(encapsulate(argumentType, arg));
argTypes.add(argumentType);
}
return visitor.visitFunction(
formula,
args.build(),
FunctionDeclarationImpl.of(
getAppName(f),
getDeclarationKind(f),
argTypes.build(),
getFormulaType(f),
Native.getAppDecl(environment, f)));
case Z3_VAR_AST:
int deBruijnIdx = Native.getIndexValue(environment, f);
return visitor.visitBoundVariable(formula, deBruijnIdx);
case Z3_QUANTIFIER_AST:
BooleanFormula body = encapsulateBoolean(Native.getQuantifierBody(environment, f));
Quantifier q =
Native.isQuantifierForall(environment, f) ? Quantifier.FORALL : Quantifier.EXISTS;
return visitor.visitQuantifier((BooleanFormula) formula, q, getBoundVars(f), body);
case Z3_SORT_AST:
case Z3_FUNC_DECL_AST:
case Z3_UNKNOWN_AST:
default:
throw new UnsupportedOperationException(
"Input should be a formula AST, " + "got unexpected type instead");
}
}
protected String symbolToString(long symbol) {
switch (Z3_symbol_kind.fromInt(Native.getSymbolKind(environment, symbol))) {
case Z3_STRING_SYMBOL:
return Native.getSymbolString(environment, symbol);
case Z3_INT_SYMBOL:
// Bound variable.
return "#" + Native.getSymbolInt(environment, symbol);
default:
throw new UnsupportedOperationException("Unexpected state");
}
}
private List<Formula> getBoundVars(long f) {
int numBound = Native.getQuantifierNumBound(environment, f);
List<Formula> boundVars = new ArrayList<>(numBound);
for (int i = 0; i < numBound; i++) {
long varName = Native.getQuantifierBoundName(environment, f, i);
long varSort = Native.getQuantifierBoundSort(environment, f, i);
boundVars.add(
encapsulate(
getFormulaTypeFromSort(varSort), Native.mkConst(environment, varName, varSort)));
}
return boundVars;
}
private FunctionDeclarationKind getDeclarationKind(long f) {
final int arity = Native.getArity(environment, Native.getAppDecl(environment, f));
assert arity > 0
: String.format(
"Unexpected arity '%s' for formula '%s' for handling a function application.",
arity, Native.astToString(environment, f));
if (getAppName(f).equals("div0")) {
// Z3 segfaults in getDeclKind for this term (cf. https://github.com/Z3Prover/z3/issues/669)
return FunctionDeclarationKind.OTHER;
}
Z3_decl_kind decl =
Z3_decl_kind.fromInt(Native.getDeclKind(environment, Native.getAppDecl(environment, f)));
switch (decl) {
case Z3_OP_AND:
return FunctionDeclarationKind.AND;
case Z3_OP_NOT:
return FunctionDeclarationKind.NOT;
case Z3_OP_OR:
return FunctionDeclarationKind.OR;
case Z3_OP_IFF:
return FunctionDeclarationKind.IFF;
case Z3_OP_ITE:
return FunctionDeclarationKind.ITE;
case Z3_OP_XOR:
return FunctionDeclarationKind.XOR;
case Z3_OP_DISTINCT:
return FunctionDeclarationKind.DISTINCT;
case Z3_OP_IMPLIES:
return FunctionDeclarationKind.IMPLIES;
case Z3_OP_SUB:
return FunctionDeclarationKind.SUB;
case Z3_OP_ADD:
return FunctionDeclarationKind.ADD;
case Z3_OP_DIV:
return FunctionDeclarationKind.DIV;
case Z3_OP_MUL:
return FunctionDeclarationKind.MUL;
case Z3_OP_MOD:
return FunctionDeclarationKind.MODULO;
case Z3_OP_TO_INT:
return FunctionDeclarationKind.FLOOR;
case Z3_OP_TO_REAL:
return FunctionDeclarationKind.TO_REAL;
case Z3_OP_UNINTERPRETED:
return FunctionDeclarationKind.UF;
case Z3_OP_LT:
return FunctionDeclarationKind.LT;
case Z3_OP_LE:
return FunctionDeclarationKind.LTE;
case Z3_OP_GT:
return FunctionDeclarationKind.GT;
case Z3_OP_GE:
return FunctionDeclarationKind.GTE;
case Z3_OP_EQ:
return FunctionDeclarationKind.EQ;
case Z3_OP_STORE:
return FunctionDeclarationKind.STORE;
case Z3_OP_SELECT:
return FunctionDeclarationKind.SELECT;
case Z3_OP_TRUE:
case Z3_OP_FALSE:
case Z3_OP_ANUM:
case Z3_OP_AGNUM:
throw new UnsupportedOperationException("Unexpected state: constants not expected");
case Z3_OP_OEQ:
throw new UnsupportedOperationException("Unexpected state: not a proof");
case Z3_OP_UMINUS:
return FunctionDeclarationKind.UMINUS;
case Z3_OP_IDIV:
// TODO: different handling for integer division?
return FunctionDeclarationKind.DIV;
case Z3_OP_EXTRACT:
return FunctionDeclarationKind.BV_EXTRACT;
case Z3_OP_CONCAT:
return FunctionDeclarationKind.BV_CONCAT;
case Z3_OP_BNOT:
return FunctionDeclarationKind.BV_NOT;
case Z3_OP_BNEG:
return FunctionDeclarationKind.BV_NEG;
case Z3_OP_BAND:
return FunctionDeclarationKind.BV_AND;
case Z3_OP_BOR:
return FunctionDeclarationKind.BV_OR;
case Z3_OP_BXOR:
return FunctionDeclarationKind.BV_XOR;
case Z3_OP_ULT:
return FunctionDeclarationKind.BV_ULT;
case Z3_OP_SLT:
return FunctionDeclarationKind.BV_SLT;
case Z3_OP_ULEQ:
return FunctionDeclarationKind.BV_ULE;
case Z3_OP_SLEQ:
return FunctionDeclarationKind.BV_SLE;
case Z3_OP_UGT:
return FunctionDeclarationKind.BV_UGT;
case Z3_OP_SGT:
return FunctionDeclarationKind.BV_SGT;
case Z3_OP_UGEQ:
return FunctionDeclarationKind.BV_UGE;
case Z3_OP_SGEQ:
return FunctionDeclarationKind.BV_SGE;
case Z3_OP_BADD:
return FunctionDeclarationKind.BV_ADD;
case Z3_OP_BSUB:
return FunctionDeclarationKind.BV_SUB;
case Z3_OP_BMUL:
return FunctionDeclarationKind.BV_MUL;
case Z3_OP_BUDIV:
return FunctionDeclarationKind.BV_UDIV;
case Z3_OP_BSDIV:
return FunctionDeclarationKind.BV_SDIV;
case Z3_OP_BUREM:
return FunctionDeclarationKind.BV_UREM;
case Z3_OP_BSREM:
return FunctionDeclarationKind.BV_SREM;
case Z3_OP_BSHL:
return FunctionDeclarationKind.BV_SHL;
case Z3_OP_BLSHR:
return FunctionDeclarationKind.BV_LSHR;
case Z3_OP_BASHR:
return FunctionDeclarationKind.BV_ASHR;
case Z3_OP_SIGN_EXT:
return FunctionDeclarationKind.BV_SIGN_EXTENSION;
case Z3_OP_ZERO_EXT:
return FunctionDeclarationKind.BV_ZERO_EXTENSION;
case Z3_OP_FPA_NEG:
return FunctionDeclarationKind.FP_NEG;
case Z3_OP_FPA_ABS:
return FunctionDeclarationKind.FP_ABS;
case Z3_OP_FPA_MAX:
return FunctionDeclarationKind.FP_MAX;
case Z3_OP_FPA_MIN:
return FunctionDeclarationKind.FP_MIN;
case Z3_OP_FPA_SQRT:
return FunctionDeclarationKind.FP_SQRT;
case Z3_OP_FPA_SUB:
return FunctionDeclarationKind.FP_SUB;
case Z3_OP_FPA_ADD:
return FunctionDeclarationKind.FP_ADD;
case Z3_OP_FPA_DIV:
return FunctionDeclarationKind.FP_DIV;
case Z3_OP_FPA_MUL:
return FunctionDeclarationKind.FP_MUL;
case Z3_OP_FPA_LT:
return FunctionDeclarationKind.FP_LT;
case Z3_OP_FPA_LE:
return FunctionDeclarationKind.FP_LE;
case Z3_OP_FPA_GE:
return FunctionDeclarationKind.FP_GE;
case Z3_OP_FPA_GT:
return FunctionDeclarationKind.FP_GT;
case Z3_OP_FPA_EQ:
return FunctionDeclarationKind.FP_EQ;
case Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
return FunctionDeclarationKind.FP_ROUND_EVEN;
case Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
return FunctionDeclarationKind.FP_ROUND_AWAY;
case Z3_OP_FPA_RM_TOWARD_POSITIVE:
return FunctionDeclarationKind.FP_ROUND_POSITIVE;
case Z3_OP_FPA_RM_TOWARD_NEGATIVE:
return FunctionDeclarationKind.FP_ROUND_NEGATIVE;
case Z3_OP_FPA_RM_TOWARD_ZERO:
return FunctionDeclarationKind.FP_ROUND_ZERO;
case Z3_OP_FPA_ROUND_TO_INTEGRAL:
return FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL;
case Z3_OP_FPA_TO_FP_UNSIGNED:
return FunctionDeclarationKind.BV_UCASTTO_FP;
case Z3_OP_FPA_TO_SBV:
return FunctionDeclarationKind.FP_CASTTO_SBV;
case Z3_OP_FPA_TO_UBV:
return FunctionDeclarationKind.FP_CASTTO_UBV;
case Z3_OP_FPA_TO_IEEE_BV:
return FunctionDeclarationKind.FP_AS_IEEEBV;
case Z3_OP_FPA_TO_FP:
Z3_sort_kind sortKind =
Z3_sort_kind.fromInt(
Native.getSortKind(
environment, Native.getSort(environment, Native.getAppArg(environment, f, 1))));
if (Z3_sort_kind.Z3_BV_SORT == sortKind) {
return FunctionDeclarationKind.BV_SCASTTO_FP;
} else {
return FunctionDeclarationKind.FP_CASTTO_FP;
}
case Z3_OP_FPA_IS_NAN:
return FunctionDeclarationKind.FP_IS_NAN;
case Z3_OP_FPA_IS_INF:
return FunctionDeclarationKind.FP_IS_INF;
case Z3_OP_FPA_IS_ZERO:
return FunctionDeclarationKind.FP_IS_ZERO;
case Z3_OP_FPA_IS_NEGATIVE:
return FunctionDeclarationKind.FP_IS_NEGATIVE;
case Z3_OP_FPA_IS_SUBNORMAL:
return FunctionDeclarationKind.FP_IS_SUBNORMAL;
case Z3_OP_FPA_IS_NORMAL:
return FunctionDeclarationKind.FP_IS_NORMAL;
case Z3_OP_SEQ_CONCAT:
return FunctionDeclarationKind.STR_CONCAT;
case Z3_OP_SEQ_PREFIX:
return FunctionDeclarationKind.STR_PREFIX;
case Z3_OP_SEQ_SUFFIX:
return FunctionDeclarationKind.STR_SUFFIX;
case Z3_OP_SEQ_CONTAINS:
return FunctionDeclarationKind.STR_CONTAINS;
case Z3_OP_SEQ_EXTRACT:
return FunctionDeclarationKind.STR_SUBSTRING;
case Z3_OP_SEQ_REPLACE:
return FunctionDeclarationKind.STR_REPLACE;
case Z3_OP_SEQ_AT:
return FunctionDeclarationKind.STR_CHAR_AT;
case Z3_OP_SEQ_LENGTH:
return FunctionDeclarationKind.STR_LENGTH;
case Z3_OP_SEQ_INDEX:
return FunctionDeclarationKind.STR_INDEX_OF;
case Z3_OP_SEQ_TO_RE:
return FunctionDeclarationKind.STR_TO_RE;
case Z3_OP_SEQ_IN_RE:
return FunctionDeclarationKind.STR_IN_RE;
case Z3_OP_STR_TO_INT:
return FunctionDeclarationKind.STR_TO_INT;
case Z3_OP_INT_TO_STR:
return FunctionDeclarationKind.INT_TO_STR;
case Z3_OP_STRING_LT:
return FunctionDeclarationKind.STR_LT;
case Z3_OP_STRING_LE:
return FunctionDeclarationKind.STR_LE;
case Z3_OP_RE_PLUS:
return FunctionDeclarationKind.RE_PLUS;
case Z3_OP_RE_STAR:
return FunctionDeclarationKind.RE_STAR;
case Z3_OP_RE_OPTION:
return FunctionDeclarationKind.RE_OPTIONAL;
case Z3_OP_RE_CONCAT:
return FunctionDeclarationKind.RE_CONCAT;
case Z3_OP_RE_UNION:
return FunctionDeclarationKind.RE_UNION;
case Z3_OP_RE_RANGE:
return FunctionDeclarationKind.RE_RANGE;
case Z3_OP_RE_INTERSECT:
return FunctionDeclarationKind.RE_INTERSECT;
case Z3_OP_RE_COMPLEMENT:
return FunctionDeclarationKind.RE_COMPLEMENT;
default:
return FunctionDeclarationKind.OTHER;
}
}
/**
* @param value Z3_ast
* @return Whether the value is a constant and can be passed to {@link #convertValue(Long)}.
*/
public boolean isConstant(long value) {
return Native.isNumeralAst(environment, value)
|| Native.isAlgebraicNumber(environment, value)
|| Native.isString(environment, value)
|| isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE)
|| isOP(environment, value, Z3_decl_kind.Z3_OP_FALSE);
}
/**
* @param value Z3_ast representing a constant value.
* @return {@link BigInteger} or {@link Double} or {@link Rational} or {@link Boolean} or {@link
* FloatingPointRoundingMode} or {@link String}.
*/
@Override
public Object convertValue(Long value) {
if (!isConstant(value)) {
return null;
}
Native.incRef(environment, value);
Object constantValue =
Z3_CONSTANTS.get(Native.getDeclKind(environment, Native.getAppDecl(environment, value)));
if (constantValue != null) {
return constantValue;
}
try {
FormulaType<?> type = getFormulaType(value);
if (type.isBooleanType()) {
return isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE);
} else if (type.isIntegerType()) {
return new BigInteger(Native.getNumeralString(environment, value));
} else if (type.isRationalType()) {
Rational ratValue = Rational.ofString(Native.getNumeralString(environment, value));
return ratValue.isIntegral() ? ratValue.getNum() : ratValue;
} else if (type.isStringType()) {
return Native.getString(environment, value);
} else if (type.isBitvectorType()) {
return new BigInteger(Native.getNumeralString(environment, value));
} else if (type.isFloatingPointType()) {
// Converting to Rational first.
return convertValue(Native.simplify(environment, Native.mkFpaToReal(environment, value)));
} else if (type.isEnumerationType()) {
return Native.astToString(environment, value);
} else {
// Explicitly crash on unknown type.
throw new IllegalArgumentException("Unexpected type encountered: " + type);
}
} finally {
Native.decRef(environment, value);
}
}
@Override
public Long declareUFImpl(String pName, Long returnType, List<Long> pArgTypes) {
long symbol = Native.mkStringSymbol(environment, pName);
long[] sorts = Longs.toArray(pArgTypes);
long func = Native.mkFuncDecl(environment, symbol, sorts.length, sorts, returnType);
Native.incRef(environment, func);
symbolsToDeclarations.put(pName, func);
return func;
}
@Override
public Long callFunctionImpl(Long declaration, List<Long> args) {
return Native.mkApp(environment, declaration, args.size(), Longs.toArray(args));
}
@Override
protected Long getBooleanVarDeclarationImpl(Long pLong) {
return Native.getAppDecl(getEnv(), pLong);
}
/** returns, if the function of the expression is the given operation. */
static boolean isOP(long z3context, long expr, Z3_decl_kind op) {
if (!Native.isApp(z3context, expr)) {
return false;
}
long decl = Native.getAppDecl(z3context, expr);
return Native.getDeclKind(z3context, decl) == op.toInt();
}
/**
* Apply multiple tactics in sequence.
*
* @throws InterruptedException thrown by JNI code in case of termination request
* @throws SolverException thrown by JNI code in case of error
*/
public long applyTactics(long z3context, final Long pF, String... pTactics)
throws InterruptedException, SolverException {
long overallResult = pF;
for (String tactic : pTactics) {
overallResult = applyTactic(z3context, overallResult, tactic);
}
return overallResult;
}
/**
* Apply tactic on a Z3_ast object, convert the result back to Z3_ast.
*
* @param z3context Z3_context
* @param tactic Z3 Tactic Name
* @param pF Z3_ast
* @return Z3_ast
* @throws InterruptedException If execution gets interrupted.
*/
public long applyTactic(long z3context, long pF, String tactic) throws InterruptedException {
long tacticObject = Native.mkTactic(z3context, tactic);
Native.tacticIncRef(z3context, tacticObject);
long goal = Native.mkGoal(z3context, true, false, false);
Native.goalIncRef(z3context, goal);
Native.goalAssert(z3context, goal, pF);
long result;
try {
result = Native.tacticApply(z3context, tacticObject, goal);
} catch (Z3Exception exp) {
throw handleZ3Exception(exp);
}
try {
return applyResultToAST(z3context, result);
} finally {
Native.goalDecRef(z3context, goal);
Native.tacticDecRef(z3context, tacticObject);
}
}
private long applyResultToAST(long z3context, long applyResult) {
int subgoalsCount = Native.applyResultGetNumSubgoals(z3context, applyResult);
long[] goalFormulas = new long[subgoalsCount];
for (int i = 0; i < subgoalsCount; i++) {
long subgoal = Native.applyResultGetSubgoal(z3context, applyResult, i);
goalFormulas[i] = goalToAST(z3context, subgoal);
}
return goalFormulas.length == 1
? goalFormulas[0]
: Native.mkOr(z3context, goalFormulas.length, goalFormulas);
}
private long goalToAST(long z3context, long goal) {
int subgoalFormulasCount = Native.goalSize(z3context, goal);
long[] subgoalFormulas = new long[subgoalFormulasCount];
for (int k = 0; k < subgoalFormulasCount; k++) {
subgoalFormulas[k] = Native.goalFormula(z3context, goal, k);
}
return subgoalFormulas.length == 1
? subgoalFormulas[0]
: Native.mkAnd(z3context, subgoalFormulas.length, subgoalFormulas);
}
/** Closing the context. */
public void forceClose() {
cleanupReferences();
// Force clean all ASTs, even those which were not GC'd yet.
// Is a no-op if phantom reference handling is not enabled.
for (long ast : referenceMap.values()) {
Native.decRef(getEnv(), ast);
}
}
/**
* get a previously created application declaration, or <code>NULL</code> if the symbol is
* unknown.
*/
@Nullable Long getKnownDeclaration(String symbolName) {
return symbolsToDeclarations.get(symbolName);
}
}
| 36,637 | 37.729387 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3FormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.Z3Exception;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.sosy_lab.common.Appender;
import org.sosy_lab.common.Appenders;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager;
final class Z3FormulaManager extends AbstractFormulaManager<Long, Long, Long, Long> {
private final Z3FormulaCreator formulaCreator;
@SuppressWarnings("checkstyle:parameternumber")
Z3FormulaManager(
Z3FormulaCreator pFormulaCreator,
Z3UFManager pFunctionManager,
Z3BooleanFormulaManager pBooleanManager,
Z3IntegerFormulaManager pIntegerManager,
Z3RationalFormulaManager pRationalManager,
Z3BitvectorFormulaManager pBitpreciseManager,
Z3FloatingPointFormulaManager pFloatingPointManager,
Z3QuantifiedFormulaManager pQuantifiedManager,
Z3ArrayFormulaManager pArrayManager,
Z3StringFormulaManager pStringManager,
Z3EnumerationFormulaManager pEnumerationManager) {
super(
pFormulaCreator,
pFunctionManager,
pBooleanManager,
pIntegerManager,
pRationalManager,
pBitpreciseManager,
pFloatingPointManager,
pQuantifiedManager,
pArrayManager,
null,
pStringManager,
pEnumerationManager);
formulaCreator = pFormulaCreator;
}
@Override
public BooleanFormula parse(String str) throws IllegalArgumentException {
// Z3 does not access the existing symbols on its own,
// but requires all symbols as part of the query.
// Thus, we track the used symbols on our own and give them to the parser call, if required.
// Later, we collect all symbols from the parsed query and
// define them again to have them tracked.
final long env = getEnvironment();
// JavaSMT does currently not allow defining new sorts, future work?
long[] sortSymbols = new long[0];
long[] sorts = new long[0];
// first step: lets try to parse the query directly, without additional information
List<Long> declSymbols = new ArrayList<>();
List<Long> decls = new ArrayList<>();
long e = 0;
boolean finished = false;
while (!finished) {
try {
e =
Native.parseSmtlib2String(
env,
str,
sorts.length,
sortSymbols,
sorts,
declSymbols.size(),
Longs.toArray(declSymbols),
Longs.toArray(decls));
finished = true;
} catch (Z3Exception nested) {
// get the missing symbol and restart the parsing with them
Pattern pattern =
Pattern.compile(
"\\(error \"line \\d+ column \\d+: unknown constant"
+ " (?<name>.*?)\\s?(?<sorts>\\(.*\\))?\\s?\\\"\\)\\n");
Matcher matcher = pattern.matcher(nested.getMessage());
if (matcher.matches()) {
String missingSymbol = matcher.group(1);
Long appDecl = formulaCreator.getKnownDeclaration(missingSymbol);
if (appDecl != null) { // if the symbol is known, then use it
declSymbols.add(Native.mkStringSymbol(env, missingSymbol));
decls.add(appDecl);
continue; // restart the parsing
}
}
throw new IllegalArgumentException(nested);
}
}
Preconditions.checkState(e != 0, "parsing aborted");
final int size = Native.astVectorSize(env, e);
Preconditions.checkState(
size == 1, "parsing expects exactly one asserted term, but got %s terms", size);
final long term = Native.astVectorGet(env, e, 0);
// last step: all parsed symbols need to be declared again to have them tracked in the creator.
declareAllSymbols(term);
return getFormulaCreator().encapsulateBoolean(term);
}
@SuppressWarnings("CheckReturnValue")
private void declareAllSymbols(final long term) {
final long env = getEnvironment();
final Map<String, Long> symbols = formulaCreator.extractVariablesAndUFs(term, true);
for (Map.Entry<String, Long> symbol : symbols.entrySet()) {
long sym = symbol.getValue();
String name = symbol.getKey();
assert Native.isApp(env, sym);
int arity = Native.getAppNumArgs(env, sym);
if (arity == 0) { // constants
formulaCreator.makeVariable(Native.getSort(env, sym), name);
} else {
ImmutableList.Builder<Long> argTypes = ImmutableList.builder();
for (int j = 0; j < arity; j++) {
argTypes.add(Native.getSort(env, Native.getAppArg(env, sym, j)));
}
formulaCreator.declareUFImpl(name, Native.getSort(env, sym), argTypes.build());
}
}
}
@Override
protected BooleanFormula applyQELightImpl(BooleanFormula pF) throws InterruptedException {
return applyTacticImpl(pF, "qe-light");
}
@Override
protected BooleanFormula applyCNFImpl(BooleanFormula pF) throws InterruptedException {
return applyTacticImpl(pF, "tseitin-cnf");
}
@Override
protected BooleanFormula applyNNFImpl(BooleanFormula pF) throws InterruptedException {
return applyTacticImpl(pF, "nnf");
}
private BooleanFormula applyTacticImpl(BooleanFormula pF, String tacticName)
throws InterruptedException {
long out =
formulaCreator.applyTactic(getFormulaCreator().getEnv(), extractInfo(pF), tacticName);
return formulaCreator.encapsulateBoolean(out);
}
@Override
public Appender dumpFormula(final Long expr) {
assert getFormulaCreator().getFormulaType(expr) == FormulaType.BooleanType
: "Only BooleanFormulas may be dumped";
return Appenders.fromToStringMethod(
new Object() {
@Override
public String toString() {
// Serializing a solver is the simplest way to dump a formula in Z3,
// cf https://github.com/Z3Prover/z3/issues/397
long z3solver = Native.mkSolver(getEnvironment());
Native.solverIncRef(getEnvironment(), z3solver);
Native.solverAssert(getEnvironment(), z3solver, expr);
String serialized = Native.solverToString(getEnvironment(), z3solver);
Native.solverDecRef(getEnvironment(), z3solver);
return serialized;
}
});
}
@Override
protected Long simplify(Long pF) throws InterruptedException {
try {
return Native.simplify(getFormulaCreator().getEnv(), pF);
} catch (Z3Exception exp) {
throw formulaCreator.handleZ3Exception(exp);
}
}
@Override
public <T extends Formula> T substitute(
final T f, final Map<? extends Formula, ? extends Formula> fromToMapping) {
long[] changeFrom = new long[fromToMapping.size()];
long[] changeTo = new long[fromToMapping.size()];
int idx = 0;
for (Map.Entry<? extends Formula, ? extends Formula> e : fromToMapping.entrySet()) {
changeFrom[idx] = extractInfo(e.getKey());
changeTo[idx] = extractInfo(e.getValue());
idx++;
}
FormulaType<T> type = getFormulaType(f);
return getFormulaCreator()
.encapsulate(
type,
Native.substitute(
getFormulaCreator().getEnv(),
extractInfo(f),
fromToMapping.size(),
changeFrom,
changeTo));
}
@Override
public BooleanFormula translateFrom(BooleanFormula other, FormulaManager otherManager) {
if (otherManager instanceof Z3FormulaManager) {
long otherZ3Context = ((Z3FormulaManager) otherManager).getEnvironment();
if (otherZ3Context == getEnvironment()) {
// Same context.
return other;
} else {
// Z3-to-Z3 translation.
long translatedAST = Native.translate(otherZ3Context, extractInfo(other), getEnvironment());
return getFormulaCreator().encapsulateBoolean(translatedAST);
}
}
return super.translateFrom(other, otherManager);
}
}
| 8,647 | 34.588477 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3IntegerFormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.microsoft.z3.Native;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
class Z3IntegerFormulaManager extends Z3NumeralFormulaManager<IntegerFormula, IntegerFormula>
implements IntegerFormulaManager {
Z3IntegerFormulaManager(Z3FormulaCreator pCreator, NonLinearArithmetic pNonLinearArithmetic) {
super(pCreator, pNonLinearArithmetic);
}
@Override
protected long getNumeralType() {
return getFormulaCreator().getIntegerType();
}
@Override
protected Long makeNumberImpl(double pNumber) {
return makeNumberImpl((long) pNumber);
}
@Override
protected Long makeNumberImpl(BigDecimal pNumber) {
return decimalAsInteger(pNumber);
}
@Override
public Long modulo(Long pNumber1, Long pNumber2) {
return Native.mkMod(z3context, pNumber1, pNumber2);
}
@Override
protected Long modularCongruence(Long pNumber1, Long pNumber2, long pModulo) {
long n = makeNumberImpl(pModulo);
Native.incRef(z3context, n);
try {
return modularCongruence0(pNumber1, pNumber2, makeNumberImpl(pModulo));
} finally {
Native.decRef(z3context, n);
}
}
@Override
protected Long modularCongruence(Long pNumber1, Long pNumber2, BigInteger pModulo) {
long n = makeNumberImpl(pModulo);
Native.incRef(z3context, n);
try {
return modularCongruence0(pNumber1, pNumber2, makeNumberImpl(pModulo));
} finally {
Native.decRef(z3context, n);
}
}
protected Long modularCongruence0(Long pNumber1, Long pNumber2, Long n) {
// ((_ divisible n) x) <==> (= x (* n (div x n)))
long x = subtract(pNumber1, pNumber2);
Native.incRef(z3context, x);
long div = Native.mkDiv(z3context, x, n);
Native.incRef(z3context, div);
long mul = Native.mkMul(z3context, 2, new long[] {n, div});
Native.incRef(z3context, mul);
try {
return Native.mkEq(z3context, x, mul);
} finally {
Native.decRef(z3context, x);
Native.decRef(z3context, div);
Native.decRef(z3context, mul);
}
}
}
| 2,436 | 28.361446 | 96 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3Model.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.base.Preconditions;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.microsoft.z3.Native;
import com.microsoft.z3.Native.LongPtr;
import com.microsoft.z3.enumerations.Z3_decl_kind;
import com.microsoft.z3.enumerations.Z3_sort_kind;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.sosy_lab.java_smt.basicimpl.AbstractModel;
import org.sosy_lab.java_smt.basicimpl.AbstractProver;
final class Z3Model extends AbstractModel<Long, Long, Long> {
private final long model;
private final long z3context;
private static final Pattern Z3_IRRELEVANT_MODEL_TERM_PATTERN = Pattern.compile(".*![0-9]+");
private final Z3FormulaCreator z3creator;
Z3Model(AbstractProver<?> pProver, long z3context, long z3model, Z3FormulaCreator pCreator) {
super(pProver, pCreator);
Native.modelIncRef(z3context, z3model);
model = z3model;
this.z3context = z3context;
z3creator = pCreator;
}
@Override
public ImmutableList<ValueAssignment> asList() {
Preconditions.checkState(!isClosed());
ImmutableList.Builder<ValueAssignment> out = ImmutableList.builder();
// Iterate through constants.
for (int constIdx = 0; constIdx < Native.modelGetNumConsts(z3context, model); constIdx++) {
long keyDecl = Native.modelGetConstDecl(z3context, model, constIdx);
Native.incRef(z3context, keyDecl);
out.addAll(getConstAssignments(keyDecl));
Native.decRef(z3context, keyDecl);
}
// Iterate through function applications.
for (int funcIdx = 0; funcIdx < Native.modelGetNumFuncs(z3context, model); funcIdx++) {
long funcDecl = Native.modelGetFuncDecl(z3context, model, funcIdx);
Native.incRef(z3context, funcDecl);
if (!isInternalSymbol(funcDecl)) {
String functionName = z3creator.symbolToString(Native.getDeclName(z3context, funcDecl));
out.addAll(getFunctionAssignments(funcDecl, funcDecl, functionName));
}
Native.decRef(z3context, funcDecl);
}
return out.build();
}
/**
* The symbol "!" is part of temporary symbols used for quantified formulas or aliases. This
* method is only a heuristic, because the user can also create a symbol containing "!".
*/
private boolean isInternalSymbol(long funcDecl) {
switch (Z3_decl_kind.fromInt(Native.getDeclKind(z3context, funcDecl))) {
case Z3_OP_SELECT:
case Z3_OP_ARRAY_EXT:
return true;
default:
return Z3_IRRELEVANT_MODEL_TERM_PATTERN
.matcher(z3creator.symbolToString(Native.getDeclName(z3context, funcDecl)))
.matches();
}
}
/**
* @return ValueAssignments for a constant declaration in the model
*/
private Collection<ValueAssignment> getConstAssignments(long keyDecl) {
Preconditions.checkArgument(
Native.getArity(z3context, keyDecl) == 0, "Declaration is not a constant");
long var = Native.mkApp(z3context, keyDecl, 0, new long[] {});
long value = Native.modelGetConstInterp(z3context, model, keyDecl);
checkReturnValue(value, keyDecl);
Native.incRef(z3context, value);
long equality = Native.mkEq(z3context, var, value);
Native.incRef(z3context, equality);
try {
long symbol = Native.getDeclName(z3context, keyDecl);
if (z3creator.isConstant(value)) {
return ImmutableList.of(
new ValueAssignment(
z3creator.encapsulateWithTypeOf(var),
z3creator.encapsulateWithTypeOf(value),
z3creator.encapsulateBoolean(equality),
z3creator.symbolToString(symbol),
z3creator.convertValue(value),
ImmutableList.of()));
} else if (Native.isAsArray(z3context, value)) {
long arrayFormula = Native.mkConst(z3context, symbol, Native.getSort(z3context, value));
Native.incRef(z3context, arrayFormula);
return getArrayAssignments(symbol, arrayFormula, value, ImmutableList.of());
} else if (Native.isApp(z3context, value)) {
long decl = Native.getAppDecl(z3context, value);
Native.incRef(z3context, decl);
Z3_sort_kind sortKind =
Z3_sort_kind.fromInt(Native.getSortKind(z3context, Native.getSort(z3context, value)));
assert sortKind == Z3_sort_kind.Z3_ARRAY_SORT : "unexpected sort: " + sortKind;
try {
return getConstantArrayAssignment(symbol, value, decl);
} finally {
Native.decRef(z3context, decl);
}
}
throw new UnsupportedOperationException(
"unknown model evaluation: " + Native.astToString(z3context, value));
} finally {
// cleanup outdated data
Native.decRef(z3context, value);
}
}
/** unrolls an constant array assignment. */
private Collection<ValueAssignment> getConstantArrayAssignment(
long arraySymbol, long value, long decl) {
long arrayFormula = Native.mkConst(z3context, arraySymbol, Native.getSort(z3context, value));
Native.incRef(z3context, arrayFormula);
Z3_decl_kind declKind = Z3_decl_kind.fromInt(Native.getDeclKind(z3context, decl));
int numArgs = Native.getAppNumArgs(z3context, value);
List<ValueAssignment> out = new ArrayList<>();
// avoid doubled ValueAssignments for cases like "(store (store ARR 0 0) 0 1)",
// where we could (but should not!) unroll the array into "[ARR[0]=1, ARR[0]=1]"
Set<Long> indizes = new HashSet<>();
// unroll an array...
while (Z3_decl_kind.Z3_OP_STORE == declKind) {
assert numArgs == 3;
long arrayIndex = Native.getAppArg(z3context, value, 1);
Native.incRef(z3context, arrayIndex);
if (indizes.add(arrayIndex)) {
long select = Native.mkSelect(z3context, arrayFormula, arrayIndex);
Native.incRef(z3context, select);
long nestedValue = Native.getAppArg(z3context, value, 2);
Native.incRef(z3context, nestedValue);
long equality = Native.mkEq(z3context, select, nestedValue);
Native.incRef(z3context, equality);
out.add(
new ValueAssignment(
z3creator.encapsulateWithTypeOf(select),
z3creator.encapsulateWithTypeOf(nestedValue),
z3creator.encapsulateBoolean(equality),
z3creator.symbolToString(arraySymbol),
z3creator.convertValue(nestedValue),
ImmutableList.of(evaluateImpl(arrayIndex))));
}
Native.decRef(z3context, arrayIndex);
// recursive unrolling
value = Native.getAppArg(z3context, value, 0);
decl = Native.getAppDecl(z3context, value);
declKind = Z3_decl_kind.fromInt(Native.getDeclKind(z3context, decl));
numArgs = Native.getAppNumArgs(z3context, value);
}
// ...until its end
if (Z3_decl_kind.Z3_OP_CONST_ARRAY == declKind) {
assert numArgs == 1;
// We have an array of zeros (=default value) as "((as const (Array Int Int)) 0)".
// There is no way of modeling a whole array, thus we ignore it.
}
return out;
}
/**
* Z3 models an array as an uninterpreted function.
*
* @return a list of assignments {@code a[1]=0; a[2]=0; a[5]=0}.
*/
private Collection<ValueAssignment> getArrayAssignments(
long arraySymbol, long arrayFormula, long value, List<Object> upperIndices) {
long evalDecl = Native.getAsArrayFuncDecl(z3context, value);
Native.incRef(z3context, evalDecl);
long interp = Native.modelGetFuncInterp(z3context, model, evalDecl);
checkReturnValue(interp, evalDecl);
Native.funcInterpIncRef(z3context, interp);
Collection<ValueAssignment> lst = new ArrayList<>();
// get all assignments for the array
int numInterpretations = Native.funcInterpGetNumEntries(z3context, interp);
for (int interpIdx = 0; interpIdx < numInterpretations; interpIdx++) {
long entry = Native.funcInterpGetEntry(z3context, interp, interpIdx);
Native.funcEntryIncRef(z3context, entry);
long arrayValue = Native.funcEntryGetValue(z3context, entry);
Native.incRef(z3context, arrayValue);
int noArgs = Native.funcEntryGetNumArgs(z3context, entry);
assert noArgs == 1 : "array modelled as UF is expected to have only one parameter, aka index";
long arrayIndex = Native.funcEntryGetArg(z3context, entry, 0);
Native.incRef(z3context, arrayIndex);
long select = Native.mkSelect(z3context, arrayFormula, arrayIndex);
Native.incRef(z3context, select);
List<Object> innerIndices = new ArrayList<>(upperIndices);
innerIndices.add(evaluateImpl(arrayIndex));
if (z3creator.isConstant(arrayValue)) {
long equality = Native.mkEq(z3context, select, arrayValue);
Native.incRef(z3context, equality);
lst.add(
new ValueAssignment(
z3creator.encapsulateWithTypeOf(select),
z3creator.encapsulateWithTypeOf(arrayValue),
z3creator.encapsulateBoolean(equality),
z3creator.symbolToString(arraySymbol),
z3creator.convertValue(arrayValue),
innerIndices));
} else if (Native.isAsArray(z3context, arrayValue)) {
lst.addAll(getArrayAssignments(arraySymbol, select, arrayValue, innerIndices));
}
Native.decRef(z3context, arrayIndex);
Native.funcEntryDecRef(z3context, entry);
}
Native.funcInterpDecRef(z3context, interp);
Native.decRef(z3context, evalDecl);
return lst;
}
private void checkReturnValue(long value, long funcDecl) {
if (value == 0) {
throw new VerifyException(
"Z3 unexpectedly claims that the value of "
+ Native.funcDeclToString(z3context, funcDecl)
+ " does not matter in model.");
}
}
/**
* get all ValueAssignments for a function declaration in the model.
*
* @param evalDecl function declaration where the evaluation comes from
* @param funcDecl function declaration where the function name comes from
* @param functionName the name of the funcDecl
*/
private Collection<ValueAssignment> getFunctionAssignments(
long evalDecl, long funcDecl, String functionName) {
long interp = Native.modelGetFuncInterp(z3context, model, evalDecl);
checkReturnValue(interp, evalDecl);
Native.funcInterpIncRef(z3context, interp);
List<ValueAssignment> lst = new ArrayList<>();
int numInterpretations = Native.funcInterpGetNumEntries(z3context, interp);
if (numInterpretations == 0) {
// we found an alias in the model, follow the alias
long elseInterp = Native.funcInterpGetElse(z3context, interp);
Native.incRef(z3context, elseInterp);
long aliasDecl = Native.getAppDecl(z3context, elseInterp);
Native.incRef(z3context, aliasDecl);
if (isInternalSymbol(aliasDecl)) {
lst.addAll(getFunctionAssignments(aliasDecl, funcDecl, functionName));
// TODO Can we guarantee termination of this recursive call?
// A chain of aliases should end after several steps.
} else {
// ignore functionDeclarations like "ite", "and",...
}
Native.decRef(z3context, aliasDecl);
Native.decRef(z3context, elseInterp);
} else {
for (int interpIdx = 0; interpIdx < numInterpretations; interpIdx++) {
long entry = Native.funcInterpGetEntry(z3context, interp, interpIdx);
Native.funcEntryIncRef(z3context, entry);
long entryValue = Native.funcEntryGetValue(z3context, entry);
if (z3creator.isConstant(entryValue)) {
lst.add(getFunctionAssignment(functionName, funcDecl, entry, entryValue));
} else {
// ignore values of complex types, e.g. Arrays
}
Native.funcEntryDecRef(z3context, entry);
}
}
Native.funcInterpDecRef(z3context, interp);
return lst;
}
/**
* @return ValueAssignment for an entry (one evaluation) of an uninterpreted function in the
* model.
*/
private ValueAssignment getFunctionAssignment(
String functionName, long funcDecl, long entry, long entryValue) {
Object value = z3creator.convertValue(entryValue);
int numArgs = Native.funcEntryGetNumArgs(z3context, entry);
long[] args = new long[numArgs];
List<Object> argumentInterpretation = new ArrayList<>();
for (int k = 0; k < numArgs; k++) {
long arg = Native.funcEntryGetArg(z3context, entry, k);
Native.incRef(z3context, arg);
// indirect assignments
assert !Native.isAsArray(z3context, arg)
: String.format(
"unexpected array-reference '%s' as evaluation of a UF parameter for UF '%s'.",
Native.astToString(z3context, arg), Native.funcDeclToString(z3context, funcDecl));
argumentInterpretation.add(z3creator.convertValue(arg));
args[k] = arg;
}
long func = Native.mkApp(z3context, funcDecl, args.length, args);
// Clean up memory.
for (long arg : args) {
Native.decRef(z3context, arg);
}
long equality = Native.mkEq(z3context, func, entryValue);
Native.incRef(z3context, equality);
return new ValueAssignment(
z3creator.encapsulateWithTypeOf(func),
z3creator.encapsulateWithTypeOf(entryValue),
z3creator.encapsulateBoolean(equality),
functionName,
value,
argumentInterpretation);
}
@Override
public String toString() {
Preconditions.checkState(!isClosed());
return Native.modelToString(z3context, model);
}
@Override
public void close() {
if (!isClosed()) {
Native.modelDecRef(z3context, model);
}
super.close();
}
@Override
protected Long evalImpl(Long formula) {
LongPtr resultPtr = new LongPtr();
boolean satisfiableModel = Native.modelEval(z3context, model, formula, false, resultPtr);
Preconditions.checkState(satisfiableModel);
if (resultPtr.value == 0) {
// unknown evaluation
return null;
} else {
Native.incRef(z3context, resultPtr.value);
return resultPtr.value;
}
}
}
| 14,497 | 36.079284 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3NumeralFormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import java.math.BigInteger;
import java.util.List;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager;
@SuppressWarnings("ClassTypeParameterName")
abstract class Z3NumeralFormulaManager<
ParamFormulaType extends NumeralFormula, ResultFormulaType extends NumeralFormula>
extends AbstractNumeralFormulaManager<
Long, Long, Long, ParamFormulaType, ResultFormulaType, Long> {
protected final long z3context;
Z3NumeralFormulaManager(Z3FormulaCreator pCreator, NonLinearArithmetic pNonLinearArithmetic) {
super(pCreator, pNonLinearArithmetic);
this.z3context = pCreator.getEnv();
}
protected abstract long getNumeralType();
@Override
protected boolean isNumeral(Long val) {
return Native.isNumeralAst(z3context, val);
}
@Override
protected Long makeNumberImpl(long i) {
long sort = getNumeralType();
return Native.mkInt64(z3context, i, sort);
}
@Override
protected Long makeNumberImpl(BigInteger pI) {
return makeNumberImpl(pI.toString());
}
@Override
protected Long makeNumberImpl(String pI) {
long sort = getNumeralType();
return Native.mkNumeral(z3context, pI, sort);
}
@Override
protected Long makeVariableImpl(String varName) {
long type = getNumeralType();
return getFormulaCreator().makeVariable(type, varName);
}
@Override
protected Long negate(Long pNumber) {
long sort = Native.getSort(z3context, pNumber);
long minusOne = Native.mkInt(z3context, -1, sort);
return Native.mkMul(z3context, 2, new long[] {minusOne, pNumber});
}
@Override
protected Long add(Long pNumber1, Long pNumber2) {
return Native.mkAdd(z3context, 2, new long[] {pNumber1, pNumber2});
}
@Override
protected Long sumImpl(List<Long> operands) {
return Native.mkAdd(z3context, operands.size(), Longs.toArray(operands));
}
@Override
protected Long subtract(Long pNumber1, Long pNumber2) {
return Native.mkSub(z3context, 2, new long[] {pNumber1, pNumber2});
}
@Override
protected Long divide(Long pNumber1, Long pNumber2) {
return Native.mkDiv(z3context, pNumber1, pNumber2);
}
@Override
protected Long multiply(Long pNumber1, Long pNumber2) {
return Native.mkMul(z3context, 2, new long[] {pNumber1, pNumber2});
}
@Override
protected Long equal(Long pNumber1, Long pNumber2) {
return Native.mkEq(z3context, pNumber1, pNumber2);
}
@Override
protected Long distinctImpl(List<Long> pNumbers) {
return Native.mkDistinct(z3context, pNumbers.size(), Longs.toArray(pNumbers));
}
@Override
protected Long greaterThan(Long pNumber1, Long pNumber2) {
return Native.mkGt(z3context, pNumber1, pNumber2);
}
@Override
protected Long greaterOrEquals(Long pNumber1, Long pNumber2) {
return Native.mkGe(z3context, pNumber1, pNumber2);
}
@Override
protected Long lessThan(Long pNumber1, Long pNumber2) {
return Native.mkLt(z3context, pNumber1, pNumber2);
}
@Override
protected Long lessOrEquals(Long pNumber1, Long pNumber2) {
return Native.mkLe(z3context, pNumber1, pNumber2);
}
}
| 3,507 | 27.520325 | 96 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3OptimizationProver.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.microsoft.z3.Native;
import com.microsoft.z3.Native.IntPtr;
import com.microsoft.z3.Z3Exception;
import com.microsoft.z3.enumerations.Z3_lbool;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.io.PathCounterTemplate;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
class Z3OptimizationProver extends Z3AbstractProver<Void> implements OptimizationProverEnvironment {
private final LogManager logger;
private final long z3optSolver;
@SuppressWarnings("checkstyle:parameternumber")
Z3OptimizationProver(
Z3FormulaCreator creator,
LogManager pLogger,
Z3FormulaManager pMgr,
Set<ProverOptions> pOptions,
ImmutableMap<String, Object> pSolverOptions,
ImmutableMap<String, String> pOptimizationOptions,
@Nullable PathCounterTemplate pLogfile,
ShutdownNotifier pShutdownNotifier) {
super(creator, pMgr, pOptions, pSolverOptions, pLogfile, pShutdownNotifier);
z3optSolver = Native.mkOptimize(z3context);
Native.optimizeIncRef(z3context, z3optSolver);
logger = pLogger;
// set parameters for the optimization solver
long params = Native.mkParams(z3context);
Native.paramsIncRef(z3context, params);
for (Entry<String, String> entry : pOptimizationOptions.entrySet()) {
addParameter(params, entry.getKey(), entry.getValue());
}
Native.optimizeSetParams(z3context, z3optSolver, params);
Native.paramsDecRef(z3context, params);
}
@Override
@Nullable
public Void addConstraint(BooleanFormula constraint) {
Preconditions.checkState(!closed);
long z3Constraint = creator.extractInfo(constraint);
Native.optimizeAssert(z3context, z3optSolver, z3Constraint);
return null;
}
@Override
public int maximize(Formula objective) {
Preconditions.checkState(!closed);
return Native.optimizeMaximize(z3context, z3optSolver, creator.extractInfo(objective));
}
@Override
public int minimize(Formula objective) {
Preconditions.checkState(!closed);
return Native.optimizeMinimize(z3context, z3optSolver, creator.extractInfo(objective));
}
@Override
public OptStatus check() throws InterruptedException, Z3SolverException {
Preconditions.checkState(!closed);
int status;
try {
status =
Native.optimizeCheck(
z3context,
z3optSolver,
0, // number of assumptions
null // assumptions
);
} catch (Z3Exception ex) {
throw creator.handleZ3Exception(ex);
}
if (status == Z3_lbool.Z3_L_FALSE.toInt()) {
return OptStatus.UNSAT;
} else if (status == Z3_lbool.Z3_L_UNDEF.toInt()) {
creator.shutdownNotifier.shutdownIfNecessary();
logger.log(
Level.INFO,
"Solver returned an unknown status, explanation: ",
Native.optimizeGetReasonUnknown(z3context, z3optSolver));
return OptStatus.UNDEF;
} else {
return OptStatus.OPT;
}
}
@Override
public void push() {
Preconditions.checkState(!closed);
Native.optimizePush(z3context, z3optSolver);
}
@Override
public void pop() {
Preconditions.checkState(!closed);
Native.optimizePop(z3context, z3optSolver);
}
@Override
public boolean isUnsat() throws Z3SolverException, InterruptedException {
Preconditions.checkState(!closed);
return check() == OptStatus.UNSAT;
}
@Override
public Optional<Rational> upper(int handle, Rational epsilon) {
return round(handle, epsilon, Native::optimizeGetUpperAsVector);
}
@Override
public Optional<Rational> lower(int handle, Rational epsilon) {
return round(handle, epsilon, Native::optimizeGetLowerAsVector);
}
private interface RoundingFunction {
long round(long context, long optContext, int handle);
}
private Optional<Rational> round(int handle, Rational epsilon, RoundingFunction direction) {
Preconditions.checkState(!closed);
// Z3 exposes the rounding result as a tuple (infinity, number, epsilon)
long vector = direction.round(z3context, z3optSolver, handle);
Native.astVectorIncRef(z3context, vector);
assert Native.astVectorSize(z3context, vector) == 3;
long inf = Native.astVectorGet(z3context, vector, 0);
Native.incRef(z3context, inf);
long value = Native.astVectorGet(z3context, vector, 1);
Native.incRef(z3context, value);
long eps = Native.astVectorGet(z3context, vector, 2);
Native.incRef(z3context, eps);
IntPtr ptr = new Native.IntPtr();
boolean status = Native.getNumeralInt(z3context, inf, ptr);
assert status;
if (ptr.value != 0) {
// Infinity.
return Optional.empty();
}
Rational v = Rational.ofString(Native.getNumeralString(z3context, value));
status = Native.getNumeralInt(z3context, eps, ptr);
assert status;
try {
return Optional.of(v.plus(epsilon.times(Rational.of(ptr.value))));
} finally {
Native.astVectorDecRef(z3context, vector);
Native.decRef(z3context, inf);
Native.decRef(z3context, value);
Native.decRef(z3context, eps);
}
}
@Override
protected long getZ3Model() {
return Native.optimizeGetModel(z3context, z3optSolver);
}
@Override
protected void assertContraint(long negatedModel) {
Native.optimizeAssert(z3context, z3optSolver, negatedModel);
}
@Override
public List<BooleanFormula> getUnsatCore() {
throw new UnsupportedOperationException(
"unsat core computation is not available for optimization prover environment.");
}
@Override
public Optional<List<BooleanFormula>> unsatCoreOverAssumptions(
Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException {
throw new UnsupportedOperationException(
"unsat core computation is not available for optimization prover environment.");
}
@Override
public void close() {
Preconditions.checkState(!closed);
Native.optimizeDecRef(z3context, z3optSolver);
closed = true;
}
/**
* Dumps the optimized objectives and the constraints on the solver in the SMT-lib format.
* Super-useful!
*/
@Override
public String toString() {
Preconditions.checkState(!closed);
return Native.optimizeToString(z3context, z3optSolver);
}
}
| 7,184 | 31.075893 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3QuantifiedFormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import java.util.List;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.basicimpl.AbstractQuantifiedFormulaManager;
class Z3QuantifiedFormulaManager extends AbstractQuantifiedFormulaManager<Long, Long, Long, Long> {
private final long z3context;
private final Z3FormulaCreator z3FormulaCreator;
Z3QuantifiedFormulaManager(Z3FormulaCreator creator) {
super(creator);
this.z3context = creator.getEnv();
z3FormulaCreator = creator;
}
@Override
public Long mkQuantifier(Quantifier q, List<Long> pVariables, Long pBody) {
checkArgument(!pVariables.isEmpty(), "List of quantified variables can not be empty");
return Native.mkQuantifierConst(
z3context,
q == Quantifier.FORALL,
0,
pVariables.size(),
Longs.toArray(pVariables),
0,
new long[0],
pBody);
}
@Override
protected Long eliminateQuantifiers(Long pExtractInfo)
throws SolverException, InterruptedException {
// It is recommended (personal communication with Nikolaj Bjorner)
// to run "qe-light" before "qe".
// "qe" does not perform a "qe-light" as a preprocessing on its own!
// One might want to run the tactic "ctx-solver-simplify" on the result.
return z3FormulaCreator.applyTactics(z3context, pExtractInfo, "qe-light", "qe");
}
}
| 1,779 | 30.785714 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3RationalFormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.microsoft.z3.Native;
import java.math.BigDecimal;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.RationalFormulaManager;
class Z3RationalFormulaManager extends Z3NumeralFormulaManager<NumeralFormula, RationalFormula>
implements RationalFormulaManager {
Z3RationalFormulaManager(Z3FormulaCreator pCreator, NonLinearArithmetic pNonLinearArithmetic) {
super(pCreator, pNonLinearArithmetic);
}
@Override
protected long getNumeralType() {
return getFormulaCreator().getRationalType();
}
@Override
protected Long makeNumberImpl(double pNumber) {
return makeNumberImpl(Double.toString(pNumber));
}
@Override
protected Long makeNumberImpl(BigDecimal pNumber) {
return makeNumberImpl(pNumber.toPlainString());
}
@Override
protected Long floor(Long pNumber) {
return Native.mkReal2int(z3context, pNumber);
}
}
| 1,252 | 27.477273 | 97 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3SolverContext.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.microsoft.z3.Native;
import com.microsoft.z3.enumerations.Z3_ast_print_mode;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.ShutdownNotifier.ShutdownRequestListener;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.FileOption;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.io.IO;
import org.sosy_lab.common.io.PathCounterTemplate;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager.NonLinearArithmetic;
import org.sosy_lab.java_smt.basicimpl.AbstractSolverContext;
public final class Z3SolverContext extends AbstractSolverContext {
private final ShutdownRequestListener interruptListener;
private final ShutdownNotifier shutdownNotifier;
private final LogManager logger;
private final ExtraOptions extraOptions;
private final Z3FormulaCreator creator;
private final Z3FormulaManager manager;
private boolean closed = false;
private static final String OPT_ENGINE_CONFIG_KEY = "optsmt_engine";
private static final String OPT_PRIORITY_CONFIG_KEY = "priority";
@Options(prefix = "solver.z3")
private static class ExtraOptions {
@Option(secure = true, description = "Require proofs from SMT solver")
boolean requireProofs = false;
@Option(
secure = true,
description =
"Activate replayable logging in Z3."
+ " The log can be given as an input to the solver and replayed.")
@FileOption(FileOption.Type.OUTPUT_FILE)
@Nullable Path log = null;
/** Optimization settings. */
@Option(
secure = true,
description = "Engine to use for the optimization",
values = {"basic", "farkas", "symba"})
String optimizationEngine = "basic";
@Option(
secure = true,
description = "Ordering for objectives in the optimization context",
values = {"lex", "pareto", "box"})
String objectivePrioritizationMode = "box";
private final @Nullable PathCounterTemplate logfile;
private final int randomSeed;
ExtraOptions(Configuration config, @Nullable PathCounterTemplate pLogfile, int pRandomSeed)
throws InvalidConfigurationException {
config.inject(this);
randomSeed = pRandomSeed;
logfile = pLogfile;
}
}
private Z3SolverContext(
Z3FormulaCreator pFormulaCreator,
ShutdownNotifier pShutdownNotifier,
LogManager pLogger,
Z3FormulaManager pManager,
ExtraOptions pExtraOptions) {
super(pManager);
creator = pFormulaCreator;
interruptListener = reason -> Native.interrupt(pFormulaCreator.getEnv());
shutdownNotifier = pShutdownNotifier;
pShutdownNotifier.register(interruptListener);
logger = pLogger;
manager = pManager;
extraOptions = pExtraOptions;
}
@SuppressWarnings("ParameterNumber")
public static synchronized Z3SolverContext create(
LogManager logger,
Configuration config,
ShutdownNotifier pShutdownNotifier,
@Nullable PathCounterTemplate solverLogfile,
long randomSeed,
FloatingPointRoundingMode pFloatingPointRoundingMode,
NonLinearArithmetic pNonLinearArithmetic,
Consumer<String> pLoader)
throws InvalidConfigurationException {
ExtraOptions extraOptions = new ExtraOptions(config, solverLogfile, (int) randomSeed);
// We need to load z3 in addition to z3java, because Z3's own class only loads the latter,
// but it will fail to find the former if not loaded previously.
// We load both libraries here to have all the loading in one place.
loadLibrariesWithFallback(
pLoader, ImmutableList.of("z3", "z3java"), ImmutableList.of("libz3", "libz3java"));
// disable Z3's own loading mechanism, see com.microsoft.z3.Native
System.setProperty("z3.skipLibraryLoad", "true");
if (extraOptions.log != null) {
Path absolutePath = extraOptions.log.toAbsolutePath();
try {
// Z3 segfaults if it cannot write to the file, thus we write once first
IO.writeFile(absolutePath, StandardCharsets.US_ASCII, "");
Native.openLog(absolutePath.toString());
} catch (IOException e) {
logger.logUserException(Level.WARNING, e, "Cannot write Z3 log file");
}
}
long cfg = Native.mkConfig();
if (extraOptions.requireProofs) {
Native.setParamValue(cfg, "PROOF", "true");
}
Native.globalParamSet("smt.random_seed", String.valueOf(randomSeed));
Native.globalParamSet("model.compact", "false");
final long context = Native.mkContextRc(cfg);
Native.delConfig(cfg);
long boolSort = Native.mkBoolSort(context);
Native.incRef(context, Native.sortToAst(context, boolSort));
long integerSort = Native.mkIntSort(context);
Native.incRef(context, Native.sortToAst(context, integerSort));
long realSort = Native.mkRealSort(context);
Native.incRef(context, Native.sortToAst(context, realSort));
long stringSort = Native.mkStringSort(context);
Native.incRef(context, Native.sortToAst(context, stringSort));
long regexSort = Native.mkReSort(context, stringSort);
Native.incRef(context, Native.sortToAst(context, regexSort));
// The string representations of Z3s formulas should be in SMTLib2,
// otherwise serialization wouldn't work.
Native.setAstPrintMode(context, Z3_ast_print_mode.Z3_PRINT_SMTLIB2_COMPLIANT.toInt());
Z3FormulaCreator creator =
new Z3FormulaCreator(
context,
boolSort,
integerSort,
realSort,
stringSort,
regexSort,
config,
pShutdownNotifier);
// Create managers
Z3UFManager functionTheory = new Z3UFManager(creator);
Z3BooleanFormulaManager booleanTheory = new Z3BooleanFormulaManager(creator);
Z3IntegerFormulaManager integerTheory =
new Z3IntegerFormulaManager(creator, pNonLinearArithmetic);
Z3RationalFormulaManager rationalTheory =
new Z3RationalFormulaManager(creator, pNonLinearArithmetic);
Z3BitvectorFormulaManager bitvectorTheory =
new Z3BitvectorFormulaManager(creator, booleanTheory);
Z3FloatingPointFormulaManager floatingPointTheory =
new Z3FloatingPointFormulaManager(creator, pFloatingPointRoundingMode);
Z3QuantifiedFormulaManager quantifierManager = new Z3QuantifiedFormulaManager(creator);
Z3ArrayFormulaManager arrayManager = new Z3ArrayFormulaManager(creator);
Z3StringFormulaManager stringTheory = new Z3StringFormulaManager(creator);
Z3EnumerationFormulaManager enumTheory = new Z3EnumerationFormulaManager(creator);
// Set the custom error handling
// which will throw Z3Exception
// instead of exit(1).
Native.setInternalErrorHandler(context);
Z3FormulaManager manager =
new Z3FormulaManager(
creator,
functionTheory,
booleanTheory,
integerTheory,
rationalTheory,
bitvectorTheory,
floatingPointTheory,
quantifierManager,
arrayManager,
stringTheory,
enumTheory);
return new Z3SolverContext(creator, pShutdownNotifier, logger, manager, extraOptions);
}
@Override
protected ProverEnvironment newProverEnvironment0(Set<ProverOptions> options) {
Preconditions.checkState(!closed, "solver context is already closed");
final ImmutableMap<String, Object> solverOptions =
ImmutableMap.<String, Object>builder()
.put(":random-seed", extraOptions.randomSeed)
.put(
":model",
options.contains(ProverOptions.GENERATE_MODELS)
|| options.contains(ProverOptions.GENERATE_ALL_SAT))
.put(
":unsat_core",
options.contains(ProverOptions.GENERATE_UNSAT_CORE)
|| options.contains(ProverOptions.GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS))
.buildOrThrow();
return new Z3TheoremProver(
creator, manager, options, solverOptions, extraOptions.logfile, shutdownNotifier);
}
@Override
protected InterpolatingProverEnvironment<?> newProverEnvironmentWithInterpolation0(
Set<ProverOptions> options) {
throw new UnsupportedOperationException("Z3 does not support interpolation");
}
@Override
public OptimizationProverEnvironment newOptimizationProverEnvironment0(
Set<ProverOptions> options) {
Preconditions.checkState(!closed, "solver context is already closed");
final ImmutableMap<String, Object> solverOptions =
ImmutableMap.of(":random-seed", extraOptions.randomSeed);
final ImmutableMap<String, String> optimizationOptions =
ImmutableMap.of(
OPT_ENGINE_CONFIG_KEY, extraOptions.optimizationEngine,
OPT_PRIORITY_CONFIG_KEY, extraOptions.objectivePrioritizationMode);
return new Z3OptimizationProver(
creator,
logger,
manager,
options,
solverOptions,
optimizationOptions,
extraOptions.logfile,
shutdownNotifier);
}
@Override
public String getVersion() {
Native.IntPtr major = new Native.IntPtr();
Native.IntPtr minor = new Native.IntPtr();
Native.IntPtr build = new Native.IntPtr();
Native.IntPtr revision = new Native.IntPtr();
Native.getVersion(major, minor, build, revision);
return "Z3 " + major.value + "." + minor.value + "." + build.value + "." + revision.value;
}
@Override
public Solvers getSolverName() {
return Solvers.Z3;
}
@Override
public void close() {
if (!closed) {
closed = true;
long context = creator.getEnv();
creator.forceClose();
shutdownNotifier.unregister(interruptListener);
Native.closeLog();
Native.delContext(context);
}
}
@Override
protected boolean supportsAssumptionSolving() {
return true;
}
}
| 11,069 | 36.653061 | 95 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3SolverException.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import org.sosy_lab.java_smt.api.SolverException;
/** This exception is thrown by native Z3 code, through our customized JNI bindings. */
class Z3SolverException extends SolverException {
private static final long serialVersionUID = 9047786707330265032L;
Z3SolverException(String msg) {
super(msg);
}
}
| 599 | 26.272727 | 87 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3StringFormulaManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 AlejandroSerranoMena
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import java.util.List;
import org.sosy_lab.java_smt.basicimpl.AbstractStringFormulaManager;
class Z3StringFormulaManager extends AbstractStringFormulaManager<Long, Long, Long, Long> {
private final long z3context;
Z3StringFormulaManager(Z3FormulaCreator creator) {
super(creator);
z3context = creator.getEnv();
}
@Override
protected Long makeStringImpl(String pValue) {
return Native.mkString(z3context, pValue);
}
@Override
protected Long makeVariableImpl(String varName) {
long type = getFormulaCreator().getStringType();
return getFormulaCreator().makeVariable(type, varName);
}
@Override
protected Long equal(Long pParam1, Long pParam2) {
return Native.mkEq(z3context, pParam1, pParam2);
}
@Override
protected Long greaterThan(Long pParam1, Long pParam2) {
return lessThan(pParam2, pParam1);
}
@Override
protected Long greaterOrEquals(Long pParam1, Long pParam2) {
return lessOrEquals(pParam2, pParam1);
}
@Override
protected Long lessThan(Long pParam1, Long pParam2) {
return Native.mkStrLt(z3context, pParam1, pParam2);
}
@Override
protected Long lessOrEquals(Long pParam1, Long pParam2) {
return Native.mkStrLe(z3context, pParam1, pParam2);
}
@Override
protected Long length(Long pParam) {
return Native.mkSeqLength(z3context, pParam);
}
@Override
protected Long concatImpl(List<Long> parts) {
Preconditions.checkArgument(!parts.isEmpty());
return Native.mkSeqConcat(z3context, parts.size(), Longs.toArray(parts));
}
@Override
protected Long prefix(Long prefix, Long str) {
return Native.mkSeqPrefix(z3context, prefix, str);
}
@Override
protected Long suffix(Long suffix, Long str) {
return Native.mkSeqSuffix(z3context, suffix, str);
}
@Override
protected Long in(Long str, Long regex) {
return Native.mkSeqInRe(z3context, str, regex);
}
@Override
protected Long contains(Long str, Long part) {
return Native.mkSeqContains(z3context, str, part);
}
@Override
protected Long indexOf(Long str, Long part, Long startIndex) {
return Native.mkSeqIndex(z3context, str, part, startIndex);
}
@Override
protected Long charAt(Long str, Long index) {
return Native.mkSeqAt(z3context, str, index);
}
@Override
protected Long substring(Long str, Long index, Long length) {
return Native.mkSeqExtract(z3context, str, index, length);
}
@Override
protected Long replace(Long fullStr, Long target, Long replacement) {
return Native.mkSeqReplace(z3context, fullStr, target, replacement);
}
@Override
protected Long replaceAll(Long fullStr, Long target, Long replacement) {
throw new UnsupportedOperationException();
}
@Override
protected Long makeRegexImpl(String value) {
Long str = makeStringImpl(value);
return Native.mkSeqToRe(z3context, str);
}
@Override
protected Long noneImpl() {
return Native.mkReEmpty(z3context, formulaCreator.getRegexType());
}
@Override
protected Long allImpl() {
return Native.mkReFull(z3context, formulaCreator.getRegexType());
}
@Override
protected Long allCharImpl() {
return Native.mkReAllchar(z3context, formulaCreator.getRegexType());
}
@Override
protected Long range(Long start, Long end) {
return Native.mkReRange(z3context, start, end);
}
@Override
protected Long concatRegexImpl(List<Long> parts) {
if (parts.isEmpty()) {
return noneImpl();
}
return Native.mkReConcat(z3context, parts.size(), Longs.toArray(parts));
}
@Override
protected Long union(Long pParam1, Long pParam2) {
return Native.mkReUnion(z3context, 2, new long[] {pParam1, pParam2});
}
@Override
protected Long intersection(Long pParam1, Long pParam2) {
return Native.mkReIntersect(z3context, 2, new long[] {pParam1, pParam2});
}
@Override
protected Long closure(Long pParam) {
return Native.mkReStar(z3context, pParam);
}
@Override
protected Long complement(Long pParam) {
return Native.mkReComplement(z3context, pParam);
}
@Override
protected Long toIntegerFormula(Long pParam) {
return Native.mkStrToInt(z3context, pParam);
}
@Override
protected Long toStringFormula(Long pParam) {
return Native.mkIntToStr(z3context, pParam);
}
}
| 4,688 | 24.763736 | 91 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3TheoremProver.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import com.google.common.collect.ImmutableMap;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.io.PathCounterTemplate;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
class Z3TheoremProver extends Z3AbstractProver<Void> implements ProverEnvironment {
Z3TheoremProver(
Z3FormulaCreator creator,
Z3FormulaManager pMgr,
Set<ProverOptions> pOptions,
ImmutableMap<String, Object> pSolverOptions,
@Nullable PathCounterTemplate pLogfile,
ShutdownNotifier pShutdownNotifier) {
super(creator, pMgr, pOptions, pSolverOptions, pLogfile, pShutdownNotifier);
}
@Override
@Nullable
public Void addConstraint(BooleanFormula f) throws InterruptedException {
super.addConstraint0(f);
return null;
}
}
| 1,251 | 31.102564 | 83 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/Z3UFManager.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.z3;
import org.sosy_lab.java_smt.basicimpl.AbstractUFManager;
class Z3UFManager extends AbstractUFManager<Long, Long, Long, Long> {
Z3UFManager(Z3FormulaCreator creator) {
super(creator);
}
}
| 481 | 24.368421 | 69 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/solvers/z3/package-info.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
/** Interface to the SMT solver Z3 (based on the native C API and JNI). */
@com.google.errorprone.annotations.CheckReturnValue
@javax.annotation.ParametersAreNonnullByDefault
@org.sosy_lab.common.annotations.FieldsAreNonnullByDefault
@org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault
package org.sosy_lab.java_smt.solvers.z3;
| 581 | 37.8 | 74 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ArrayFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import static org.sosy_lab.java_smt.api.FormulaType.RationalType;
import static org.sosy_lab.java_smt.api.FormulaType.StringType;
import static org.sosy_lab.java_smt.api.FormulaType.getBitvectorTypeWithSize;
import static org.sosy_lab.java_smt.api.FormulaType.getSinglePrecisionFloatingPointType;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
/** Tests Arrays for all solvers that support it. */
public class ArrayFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Before
public void init() {
requireArrays();
}
@Test
public void testIntIndexIntValue() throws SolverException, InterruptedException {
requireIntegers();
// (arr2 = store(arr1, 4, 2)) & !(select(arr2, 4) = 2)
ArrayFormulaType<IntegerFormula, IntegerFormula> type =
FormulaType.getArrayType(IntegerType, IntegerType);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num4 = imgr.makeNumber(4);
ArrayFormula<IntegerFormula, IntegerFormula> arr1 = amgr.makeArray("arr1", type);
ArrayFormula<IntegerFormula, IntegerFormula> arr2 = amgr.makeArray("arr2", type);
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, num4, num2)),
bmgr.not(imgr.equal(num2, amgr.select(arr2, num4))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not String Arrays are possible with String indexes
*/
@Test
public void testStringIndexStringValue() throws SolverException, InterruptedException {
requireStrings();
// (arr2 = store(arr1, "four", "two")) & !(select(arr2, "four") = "two")
StringFormula num2 = smgr.makeString("two");
StringFormula num4 = smgr.makeString("four");
ArrayFormula<StringFormula, StringFormula> arr1 =
amgr.makeArray("arr1", StringType, StringType);
ArrayFormula<StringFormula, StringFormula> arr2 =
amgr.makeArray("arr2", StringType, StringType);
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, num4, num2)),
bmgr.not(smgr.equal(num2, amgr.select(arr2, num4))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not String Arrays with Int indexes are possible
*/
@Test
public void testIntIndexStringValue() throws SolverException, InterruptedException {
requireStrings();
// (arr2 = store(arr1, 4, "two")) & !(select(arr2, 4) = "two")
StringFormula stringTwo = smgr.makeString("two");
IntegerFormula intFour = imgr.makeNumber(4);
ArrayFormula<IntegerFormula, StringFormula> arr1 =
amgr.makeArray("arr1", FormulaType.IntegerType, StringType);
ArrayFormula<IntegerFormula, StringFormula> arr2 =
amgr.makeArray("arr2", FormulaType.IntegerType, StringType);
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, intFour, stringTwo)),
bmgr.not(smgr.equal(stringTwo, amgr.select(arr2, intFour))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not String Arrays with bitvector indexes are possible
*/
@Test
public void testBvIndexStringValue() throws SolverException, InterruptedException {
requireStrings();
// (arr2 = store(arr1, 0100, "two")) & !(select(arr2, 0100) = "two")
StringFormula stringTwo = smgr.makeString("two");
BitvectorFormula bv4 = bvmgr.makeBitvector(4, 4);
ArrayFormula<BitvectorFormula, StringFormula> arr1 =
amgr.makeArray("arr1", getBitvectorTypeWithSize(4), StringType);
ArrayFormula<BitvectorFormula, StringFormula> arr2 =
amgr.makeArray("arr2", getBitvectorTypeWithSize(4), StringType);
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, bv4, stringTwo)),
bmgr.not(smgr.equal(stringTwo, amgr.select(arr2, bv4))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not Bitvector Arrays are possible with bv index
*/
@Test
public void testBvIndexBvValue() throws SolverException, InterruptedException {
requireBitvectors();
// (arr2 = store(arr1, 0100, 0010)) & !(select(arr2, 0100) = 0010)
BitvectorFormula num2 = bvmgr.makeBitvector(4, 2);
BitvectorFormula num4 = bvmgr.makeBitvector(4, 4);
ArrayFormula<BitvectorFormula, BitvectorFormula> arr1 =
amgr.makeArray("arr1", getBitvectorTypeWithSize(4), getBitvectorTypeWithSize(4));
ArrayFormula<BitvectorFormula, BitvectorFormula> arr2 =
amgr.makeArray("arr2", getBitvectorTypeWithSize(4), getBitvectorTypeWithSize(4));
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, num4, num2)),
bmgr.not(bvmgr.equal(num2, amgr.select(arr2, num4))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not Rational Arrays are possible with Rational index
*/
@Test
public void testRationalIndexRationalValue() throws SolverException, InterruptedException {
requireRationals();
// (arr2 = store(arr1, 4, 2)) & !(select(arr2, 4) = 2)
RationalFormula num2 = rmgr.makeNumber(2);
RationalFormula num4 = rmgr.makeNumber(4);
ArrayFormula<RationalFormula, RationalFormula> arr1 =
amgr.makeArray("arr1", RationalType, RationalType);
ArrayFormula<RationalFormula, RationalFormula> arr2 =
amgr.makeArray("arr2", RationalType, RationalType);
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, num4, num2)),
bmgr.not(rmgr.equal(num2, amgr.select(arr2, num4))));
assertThatFormula(query).isUnsatisfiable();
}
/*
* Test whether or not Float Arrays are possible with Float index
*/
@Test
public void testFloatIndexFloatValue() throws SolverException, InterruptedException {
requireFloats();
// (arr2 = store(arr1, 4.0, 2.0)) & !(select(arr2, 4.0) = 2.0)
FloatingPointFormula num2 = fpmgr.makeNumber(2, getSinglePrecisionFloatingPointType());
FloatingPointFormula num4 = fpmgr.makeNumber(4, getSinglePrecisionFloatingPointType());
ArrayFormula<FloatingPointFormula, FloatingPointFormula> arr1 =
amgr.makeArray(
"arr1", getSinglePrecisionFloatingPointType(), getSinglePrecisionFloatingPointType());
ArrayFormula<FloatingPointFormula, FloatingPointFormula> arr2 =
amgr.makeArray(
"arr2", getSinglePrecisionFloatingPointType(), getSinglePrecisionFloatingPointType());
BooleanFormula query =
bmgr.and(
amgr.equivalence(arr2, amgr.store(arr1, num4, num2)),
bmgr.not(fpmgr.equalWithFPSemantics(num2, amgr.select(arr2, num4))));
assertThatFormula(query).isUnsatisfiable();
}
}
| 7,619 | 40.413043 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/BitvectorFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.BitvectorType;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
/**
* Tests bitvectors for all solvers that support it. Notice: Boolector does not support integer
* theory or bitvectors length 1.
*/
@RunWith(Parameterized.class)
public class BitvectorFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private static final BitvectorType bvType4 = FormulaType.getBitvectorTypeWithSize(4);
@Before
public void init() {
requireBitvectors();
}
@Test
public void bvType() {
int[] testValues;
if (solver == Solvers.BOOLECTOR) {
testValues = new int[] {2, 4, 32, 64, 1000};
} else {
testValues = new int[] {1, 2, 4, 32, 64, 1000};
}
for (int i : testValues) {
BitvectorType type = FormulaType.getBitvectorTypeWithSize(i);
assertWithMessage("bitvector type size").that(type.getSize()).isEqualTo(i);
BitvectorFormula var = bvmgr.makeVariable(type, "x" + i);
BitvectorType result = (BitvectorType) mgr.getFormulaType(var);
assertWithMessage("bitvector size").that(result.getSize()).isEqualTo(i);
}
}
@Test
public void bvOne() throws SolverException, InterruptedException {
int[] testValues;
if (solver == Solvers.BOOLECTOR) {
testValues = new int[] {2, 4, 32, 64, 1000};
} else {
testValues = new int[] {1, 2, 4, 32, 64, 1000};
}
for (int i : testValues) {
BitvectorFormula var = bvmgr.makeVariable(i, "x" + i);
BitvectorFormula num0 = bvmgr.makeBitvector(i, 0);
BitvectorFormula num1 = bvmgr.makeBitvector(i, 1);
assertThatFormula(bvmgr.equal(var, num0)).isSatisfiable();
assertThatFormula(bvmgr.equal(var, num1)).isSatisfiable();
}
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public void bvTooLargeNum() {
bvmgr.makeBitvector(2, 4); // value 4 is too large for size 2
if (solver != Solvers.BOOLECTOR) {
bvmgr.makeBitvector(1, 2); // value 2 is too large for size 1
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void bvLargeNum() {
bvmgr.makeBitvector(2, 3); // value 3 should be possible for size 2
if (solver != Solvers.BOOLECTOR) {
bvmgr.makeBitvector(1, 1); // value 1 should be possible for size 1
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void bvSmallNum() {
bvmgr.makeBitvector(2, -1); // value -1 should be possible for size 2
if (solver != Solvers.BOOLECTOR) {
bvmgr.makeBitvector(1, -1); // value -1 should be possible for size 1
}
}
@Test
public void bvTooSmallNum() {
// value -4 is too small for size 2
assertThrows(IllegalArgumentException.class, () -> bvmgr.makeBitvector(2, -4));
if (solver != Solvers.BOOLECTOR) {
// value -2 is too small for size 1
assertThrows(IllegalArgumentException.class, () -> bvmgr.makeBitvector(1, -2));
}
}
@Test
public void bvModelValue32bit() throws SolverException, InterruptedException {
BitvectorFormula var = bvmgr.makeVariable(32, "var");
Map<Long, Long> values = new LinkedHashMap<>();
long int32 = 1L << 32;
// positive signed values stay equal
values.put(0L, 0L);
values.put(1L, 1L);
values.put(2L, 2L);
values.put(123L, 123L);
values.put((long) Integer.MAX_VALUE, (long) Integer.MAX_VALUE);
// positive unsigned values stay equal
values.put(Integer.MAX_VALUE + 1L, Integer.MAX_VALUE + 1L);
values.put(Integer.MAX_VALUE + 2L, Integer.MAX_VALUE + 2L);
values.put(Integer.MAX_VALUE + 123L, Integer.MAX_VALUE + 123L);
values.put(int32 - 1L, int32 - 1);
values.put(int32 - 2L, int32 - 2);
values.put(int32 - 123L, int32 - 123);
// negative signed values are converted to unsigned
values.put(-1L, int32 - 1);
values.put(-2L, int32 - 2);
values.put(-123L, int32 - 123);
values.put((long) Integer.MIN_VALUE, 1L + Integer.MAX_VALUE);
try (ProverEnvironment prover =
context.newProverEnvironment(
ProverOptions.GENERATE_MODELS, ProverOptions.GENERATE_UNSAT_CORE)) {
for (Map.Entry<Long, Long> entry : values.entrySet()) {
prover.push(bvmgr.equal(var, bvmgr.makeBitvector(32, entry.getKey())));
assertThat(prover).isSatisfiable();
try (Model model = prover.getModel()) {
Object value = model.evaluate(var);
assertThat(value).isEqualTo(BigInteger.valueOf(entry.getValue()));
}
prover.pop();
}
}
}
@Test
public void bvToInt() throws SolverException, InterruptedException {
requireBitvectorToInt();
requireIntegers();
for (int size : new int[] {1, 2, 4, 8}) {
int max = 1 << size;
// number is in range of bitsize
for (int i : new int[] {-max / 2, max - 1, 0}) {
BitvectorFormula bv = bvmgr.makeBitvector(size, i);
IntegerFormula num = imgr.makeNumber(i);
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, num))).isTautological();
IntegerFormula nSigned = bvmgr.toIntegerFormula(bv, true);
IntegerFormula nUnsigned = bvmgr.toIntegerFormula(bv, false);
if (i < max / 2) {
assertThatFormula(imgr.equal(num, nSigned)).isTautological();
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, nSigned))).isTautological();
}
if (i >= 0) {
assertThatFormula(imgr.equal(num, nUnsigned)).isTautological();
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, nUnsigned))).isTautological();
}
}
}
}
@Test
public void bvToIntEquality() throws SolverException, InterruptedException {
requireBitvectorToInt();
requireIntegers();
for (int size : new int[] {10, 16, 20, 32, 64}) {
for (int i : new int[] {1, 2, 4, 32, 64, 100}) {
// number is in range of bitsize
BitvectorFormula bv = bvmgr.makeBitvector(size, i);
IntegerFormula num = imgr.makeNumber(i);
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, num))).isTautological();
IntegerFormula nSigned = bvmgr.toIntegerFormula(bv, true);
IntegerFormula nUnsigned = bvmgr.toIntegerFormula(bv, false);
assertThatFormula(imgr.equal(num, nSigned)).isTautological();
assertThatFormula(imgr.equal(num, nUnsigned)).isTautological();
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, nSigned))).isTautological();
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, nUnsigned))).isTautological();
}
}
}
private static final int[] SOME_SIZES = new int[] {1, 2, 4, 10, 16, 20, 32, 60};
private static final int[] SOME_NUMBERS =
new int[] {0, 1, 3, 4, 8, 32, 100, 512, 100000, Integer.MAX_VALUE};
@Test
public void bvToIntEqualityWithOverflow() throws SolverException, InterruptedException {
requireBitvectorToInt();
requireIntegers();
for (int size : SOME_SIZES) {
for (int i : SOME_NUMBERS) {
// number might be larger than range of bitsize
long upperBound = 1L << size;
long iMod = i % upperBound;
IntegerFormula num = imgr.makeNumber(i);
IntegerFormula nUnsigned = imgr.makeNumber(iMod);
IntegerFormula nSigned = imgr.makeNumber(iMod < upperBound / 2 ? iMod : iMod - upperBound);
BitvectorFormula bv = bvmgr.makeBitvector(size, iMod);
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, num))).isTautological();
assertThat(mgr.getFormulaType(bvmgr.toIntegerFormula(bv, true)))
.isEqualTo(FormulaType.IntegerType);
assertThatFormula(imgr.equal(nSigned, bvmgr.toIntegerFormula(bv, true))).isTautological();
assertThatFormula(imgr.equal(nUnsigned, bvmgr.toIntegerFormula(bv, false)))
.isTautological();
}
}
}
@Test
public void bvToIntEqualityWithOverflowNegative() throws SolverException, InterruptedException {
requireBitvectorToInt();
requireIntegers();
for (int size : SOME_SIZES) {
for (int i : SOME_NUMBERS) {
// make number negative
int negI = -i;
// number might be larger than range of bitsize
long upperBound = 1L << size;
long iMod = negI % upperBound;
IntegerFormula num = imgr.makeNumber(negI);
IntegerFormula nUnsigned = imgr.makeNumber(iMod >= 0 ? iMod : iMod + upperBound);
IntegerFormula nSigned = imgr.makeNumber(iMod < -upperBound / 2 ? iMod + upperBound : iMod);
BitvectorFormula bv =
bvmgr.makeBitvector(size, iMod >= -upperBound / 2 ? iMod : iMod + upperBound);
assertThatFormula(bvmgr.equal(bv, bvmgr.makeBitvector(size, num))).isTautological();
assertThatFormula(imgr.equal(nSigned, bvmgr.toIntegerFormula(bv, true))).isTautological();
assertThatFormula(imgr.equal(nUnsigned, bvmgr.toIntegerFormula(bv, false)))
.isTautological();
}
}
}
@Test
public void bvToIntEqualityWithSymbols() throws SolverException, InterruptedException {
requireBitvectorToInt();
requireIntegers();
for (int size : new int[] {1, 2, 4}) {
IntegerFormula var = imgr.makeVariable("x_" + size);
// x == int(bv(x)) is sat for small values
assertThatFormula(
imgr.equal(var, bvmgr.toIntegerFormula(bvmgr.makeBitvector(size, var), true)))
.isSatisfiable();
// x == int(bv(x)) is unsat for large values
assertThatFormula(
bmgr.not(
imgr.equal(var, bvmgr.toIntegerFormula(bvmgr.makeBitvector(size, var), true))))
.isSatisfiable();
BitvectorFormula bvar = bvmgr.makeVariable(size, "y_" + size);
// y == bv(int(y)) is sat for all values
assertThatFormula(
bvmgr.equal(bvar, bvmgr.makeBitvector(size, bvmgr.toIntegerFormula(bvar, true))))
.isTautological();
}
}
@Test
public void bvExtractTooLargeNumEndSigned() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, 5, 0));
}
@Test
public void bvExtractTooLargeNumStartSigned() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, 4, 5));
}
@Test
public void bvExtractTooLargeNumStartAltSigned() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, 3, 4));
}
@Test
public void bvExtractNegNumEnd() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, -1, 0));
}
@Test
public void bvExtractNegNumStart() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, 1, -1));
}
@Test
public void bvExtractNegNumStartEnd() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extract(bv, -1, -1));
}
@Test
public void bvExtendNegNum() {
// Use bv > 1 because of Boolector
BitvectorFormula bv = bvmgr.makeBitvector(4, 4);
assertThrows(IllegalArgumentException.class, () -> bvmgr.extend(bv, -1, true));
}
@Test
public void bvIntArray() {
requireArrays();
assume()
.withMessage("Solver %s does not support arrays with integer index", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
BitvectorFormula bv = bvmgr.makeBitvector(4, 3);
ArrayFormula<IntegerFormula, BitvectorFormula> arr =
amgr.makeArray("arr", FormulaType.IntegerType, bvType4);
IntegerFormula index = imgr.makeNumber(12);
arr = amgr.store(arr, index, bv);
assertThat(mgr.getFormulaType(arr))
.isEqualTo(FormulaType.getArrayType(FormulaType.IntegerType, bvType4));
}
@Test
public void bvBvArray() {
requireArrays();
BitvectorFormula bv = bvmgr.makeBitvector(4, 3);
ArrayFormula<BitvectorFormula, BitvectorFormula> arr = amgr.makeArray("arr", bvType4, bvType4);
BitvectorFormula index = bvmgr.makeBitvector(4, 2);
arr = amgr.store(arr, index, bv);
assertThat(mgr.getFormulaType(arr)).isEqualTo(FormulaType.getArrayType(bvType4, bvType4));
}
@Test
public void bvDistinct() throws SolverException, InterruptedException {
for (int bitsize : new int[] {2, 4, 6}) {
if (solverToUse() == Solvers.CVC5 && bitsize > 4) {
// CVC5 runs endlessly for > 4; A issue is open for this as CVC4 can solve this in less than
// a second. See: https://github.com/cvc5/cvc5/discussions/8361
break;
}
List<BitvectorFormula> bvs = new ArrayList<>();
for (int i = 0; i < 1 << bitsize; i++) {
bvs.add(bvmgr.makeVariable(bitsize, "a" + i + "_" + bitsize));
}
assertThatFormula(bvmgr.distinct(bvs.subList(0, 1 << (bitsize - 1)))).isSatisfiable();
assertThatFormula(bvmgr.distinct(bvs)).isSatisfiable();
bvs.add(bvmgr.makeVariable(bitsize, "b" + "_" + bitsize));
assertThatFormula(bvmgr.distinct(bvs)).isUnsatisfiable();
}
}
@Test
public void bvVarDistinct() throws SolverException, InterruptedException {
BitvectorFormula a = bvmgr.makeVariable(4, "a");
BitvectorFormula num3 = bvmgr.makeBitvector(4, 3);
assertThatFormula(bvmgr.distinct(List.of(a, num3))).isSatisfiable();
assertThatFormula(bvmgr.distinct(List.of(a, a))).isUnsatisfiable();
assertThatFormula(bvmgr.distinct(List.of(num3, num3))).isUnsatisfiable();
}
}
| 15,109 | 36.680798 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/BooleanFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.truth.Truth;
import java.util.List;
import org.junit.AssumptionViolatedException;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.SolverException;
/**
* Uses bitvector theory if there is no integer theory available. Notice: Boolector does not support
* bitvectors length 1.
*/
public class BooleanFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void testVariableNamedTrue() throws SolverException, InterruptedException {
BooleanFormula var;
try {
var = bmgr.makeVariable("true");
} catch (RuntimeException e) {
throw new AssumptionViolatedException("unsupported variable name", e);
}
BooleanFormula f = bmgr.equivalence(var, bmgr.makeFalse());
assertThatFormula(f).isSatisfiable();
}
@Test
public void testVariableNamedFalse() throws SolverException, InterruptedException {
BooleanFormula var;
try {
var = bmgr.makeVariable("false");
} catch (RuntimeException e) {
throw new AssumptionViolatedException("unsupported variable name", e);
}
BooleanFormula f = bmgr.equivalence(var, bmgr.makeTrue());
assertThatFormula(f).isSatisfiable();
}
@Test
public void testConjunctionCollector() {
List<BooleanFormula> terms =
ImmutableList.of(
bmgr.makeVariable("a"),
bmgr.makeTrue(),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"));
// Syntactic equality to ensure that formula structure does not change
// when users change the method they use for creating disjunctions.
assertThatFormula(terms.stream().collect(bmgr.toConjunction())).isEqualTo(bmgr.and(terms));
}
@Test
public void testDisjunctionCollector() {
List<BooleanFormula> terms =
ImmutableList.of(
bmgr.makeVariable("a"),
bmgr.makeFalse(),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"));
// Syntactic equality to ensure that formula structure does not change
// when users change the method they use for creating disjunctions.
assertThatFormula(terms.stream().collect(bmgr.toDisjunction())).isEqualTo(bmgr.or(terms));
}
@Test
public void testConjunctionArgsExtractionEmpty() throws SolverException, InterruptedException {
requireVisitor();
BooleanFormula input = bmgr.makeBoolean(true);
Truth.assertThat(bmgr.toConjunctionArgs(input, false)).isEmpty();
assertThatFormula(bmgr.and(bmgr.toConjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void testConjunctionArgsExtraction() throws SolverException, InterruptedException {
requireIntegers();
BooleanFormula input =
bmgr.and(bmgr.makeVariable("a"), imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")));
Truth.assertThat(bmgr.toConjunctionArgs(input, false))
.isEqualTo(
ImmutableSet.of(
bmgr.makeVariable("a"), imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x"))));
assertThatFormula(bmgr.and(bmgr.toConjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void testConjunctionArgsExtractionRecursive()
throws SolverException, InterruptedException {
BooleanFormula input;
ImmutableSet<BooleanFormula> comparisonSet;
if (imgr != null) {
input =
bmgr.and(
bmgr.makeVariable("a"),
bmgr.makeBoolean(true),
bmgr.and(
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bmgr.and(
imgr.equal(imgr.makeNumber(2), imgr.makeVariable("y")),
bmgr.makeVariable("d"),
bmgr.or(bmgr.makeVariable("e"), bmgr.makeVariable("f")))),
imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")),
imgr.equal(imgr.makeNumber(2), imgr.makeVariable("y")),
bmgr.makeVariable("d"),
bmgr.or(bmgr.makeVariable("e"), bmgr.makeVariable("f")));
} else {
input =
bmgr.and(
bmgr.makeVariable("a"),
bmgr.makeBoolean(true),
bmgr.and(
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bmgr.and(
bvmgr.equal(bvmgr.makeBitvector(2, 2), bvmgr.makeVariable(2, "y")),
bmgr.makeVariable("d"),
bmgr.or(bmgr.makeVariable("e"), bmgr.makeVariable("f")))),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")),
bvmgr.equal(bvmgr.makeBitvector(2, 2), bvmgr.makeVariable(2, "y")),
bmgr.makeVariable("d"),
bmgr.or(bmgr.makeVariable("e"), bmgr.makeVariable("f")));
}
requireVisitor();
Truth.assertThat(bmgr.toConjunctionArgs(input, true)).isEqualTo(comparisonSet);
assertThatFormula(bmgr.and(bmgr.toConjunctionArgs(input, true))).isEquivalentTo(input);
assertThatFormula(bmgr.and(bmgr.toConjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void testDisjunctionArgsExtractionEmpty() throws SolverException, InterruptedException {
requireVisitor();
BooleanFormula input = bmgr.makeBoolean(false);
Truth.assertThat(bmgr.toDisjunctionArgs(input, false)).isEmpty();
assertThatFormula(bmgr.or(bmgr.toDisjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void testDisjunctionArgsExtraction() throws SolverException, InterruptedException {
BooleanFormula input;
ImmutableSet<BooleanFormula> comparisonSet;
if (imgr != null) {
input =
bmgr.or(bmgr.makeVariable("a"), imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"), imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")));
} else {
input =
bmgr.or(
bmgr.makeVariable("a"),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")));
}
requireVisitor();
Truth.assertThat(bmgr.toDisjunctionArgs(input, false)).isEqualTo(comparisonSet);
assertThatFormula(bmgr.or(bmgr.toConjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void testDisjunctionArgsExtractionRecursive()
throws SolverException, InterruptedException {
BooleanFormula input;
ImmutableSet<BooleanFormula> comparisonSet;
if (imgr != null) {
input =
bmgr.or(
bmgr.makeVariable("a"),
bmgr.makeBoolean(false),
bmgr.or(
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bmgr.or(
imgr.equal(imgr.makeNumber(2), imgr.makeVariable("y")),
bmgr.makeVariable("d"),
bmgr.and(bmgr.makeVariable("e"), bmgr.makeVariable("f")))),
imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
imgr.equal(imgr.makeNumber(1), imgr.makeVariable("x")),
imgr.equal(imgr.makeNumber(2), imgr.makeVariable("y")),
bmgr.makeVariable("d"),
bmgr.and(bmgr.makeVariable("e"), bmgr.makeVariable("f")));
} else {
input =
bmgr.or(
bmgr.makeVariable("a"),
bmgr.makeBoolean(false),
bmgr.or(
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bmgr.or(
bvmgr.equal(bvmgr.makeBitvector(2, 2), bvmgr.makeVariable(2, "y")),
bmgr.makeVariable("d"),
bmgr.and(bmgr.makeVariable("e"), bmgr.makeVariable("f")))),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")));
comparisonSet =
ImmutableSet.of(
bmgr.makeVariable("a"),
bmgr.makeVariable("b"),
bmgr.makeVariable("c"),
bvmgr.equal(bvmgr.makeBitvector(2, 1), bvmgr.makeVariable(2, "x")),
bvmgr.equal(bvmgr.makeBitvector(2, 2), bvmgr.makeVariable(2, "y")),
bmgr.makeVariable("d"),
bmgr.and(bmgr.makeVariable("e"), bmgr.makeVariable("f")));
}
requireVisitor();
Truth.assertThat(bmgr.toDisjunctionArgs(input, true)).isEqualTo(comparisonSet);
assertThatFormula(bmgr.or(bmgr.toDisjunctionArgs(input, true))).isEquivalentTo(input);
assertThatFormula(bmgr.or(bmgr.toDisjunctionArgs(input, false))).isEquivalentTo(input);
}
@Test
public void simplificationTest() {
// Boolector and CVC5 fail this as it either simplifies to much, or nothing
// TODO: maybe this is just a matter of options, check!
assume()
.withMessage(
"Solver %s fails on this test as it does not simplify any formulas.", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.BOOLECTOR, Solvers.CVC5);
BooleanFormula tru = bmgr.makeBoolean(true);
BooleanFormula fals = bmgr.makeBoolean(false);
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula y = bmgr.makeVariable("y");
// AND
Truth.assertThat(bmgr.and(tru)).isEqualTo(tru);
Truth.assertThat(bmgr.and(fals)).isEqualTo(fals);
Truth.assertThat(bmgr.and(x)).isEqualTo(x);
Truth.assertThat(bmgr.and()).isEqualTo(tru);
Truth.assertThat(bmgr.and(tru, tru)).isEqualTo(tru);
Truth.assertThat(bmgr.and(tru, x)).isEqualTo(x);
Truth.assertThat(bmgr.and(fals, x)).isEqualTo(fals);
Truth.assertThat(bmgr.and(x, x)).isEqualTo(x);
Truth.assertThat(bmgr.and(tru, tru, tru)).isEqualTo(tru);
Truth.assertThat(bmgr.and(fals, fals, fals)).isEqualTo(fals);
Truth.assertThat(bmgr.and(fals, x, x)).isEqualTo(fals);
Truth.assertThat(bmgr.and(tru, x, tru)).isEqualTo(x);
Truth.assertThat(bmgr.and(tru, tru, x, fals, y, tru, x, y)).isEqualTo(fals);
// recursive simplification needed
// Truth.assertThat(bmgr.and(x, x, x, y, y)).isEqualTo(bmgr.and(x, y));
// OR
Truth.assertThat(bmgr.or(tru)).isEqualTo(tru);
Truth.assertThat(bmgr.or(fals)).isEqualTo(fals);
Truth.assertThat(bmgr.or(x)).isEqualTo(x);
Truth.assertThat(bmgr.or()).isEqualTo(fals);
Truth.assertThat(bmgr.or(tru, tru)).isEqualTo(tru);
Truth.assertThat(bmgr.or(tru, x)).isEqualTo(tru);
Truth.assertThat(bmgr.or(fals, x)).isEqualTo(x);
Truth.assertThat(bmgr.or(x, x)).isEqualTo(x);
Truth.assertThat(bmgr.or(fals, fals, fals)).isEqualTo(fals);
Truth.assertThat(bmgr.or(tru, x, x)).isEqualTo(tru);
Truth.assertThat(bmgr.or(fals, x, fals)).isEqualTo(x);
Truth.assertThat(bmgr.or(fals, fals, x, tru, y, fals, x, y)).isEqualTo(tru);
}
@Test
public void simpleImplicationTest() throws InterruptedException, SolverException {
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula y = bmgr.makeVariable("y");
BooleanFormula z = bmgr.makeVariable("z");
BooleanFormula f = bmgr.and(bmgr.equivalence(x, y), bmgr.equivalence(x, z));
assertThatFormula(f).implies(bmgr.equivalence(y, z));
}
@Test
public void simplifiedNot() {
BooleanFormula fTrue = bmgr.makeTrue();
BooleanFormula fFalse = bmgr.makeFalse();
BooleanFormula var1 = bmgr.makeVariable("var1");
BooleanFormula var2 = bmgr.makeVariable("var2");
BooleanFormula var3 = bmgr.makeVariable("var3");
BooleanFormula var4 = bmgr.makeVariable("var4");
// simple tests
Truth.assertThat(bmgr.not(fTrue)).isEqualTo(fFalse);
Truth.assertThat(bmgr.not(fFalse)).isEqualTo(fTrue);
// one nesting level
Truth.assertThat(bmgr.not(bmgr.not(var1))).isEqualTo(var1);
// more nesting
BooleanFormula f = bmgr.and(bmgr.or(var1, bmgr.not(var2), var3), bmgr.not(var4));
Truth.assertThat(bmgr.not(bmgr.not(f))).isEqualTo(f);
}
@Test
public void simplifiedAnd() {
BooleanFormula fTrue = bmgr.makeTrue();
BooleanFormula fFalse = bmgr.makeFalse();
BooleanFormula var1 = bmgr.makeVariable("var1");
BooleanFormula var2 = bmgr.makeVariable("var2");
Truth.assertThat(bmgr.and(fTrue, fTrue)).isEqualTo(fTrue);
Truth.assertThat(bmgr.and(fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(fTrue, fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(fTrue, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.and(fFalse, var1)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(var1, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.and(fTrue, fTrue, fTrue, fTrue)).isEqualTo(fTrue);
Truth.assertThat(bmgr.and(fTrue, fFalse, fTrue)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(fTrue, fTrue, fTrue, fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(fTrue, fTrue, fTrue, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.and(fTrue, fFalse, fTrue, var1)).isEqualTo(fFalse);
Truth.assertThat(bmgr.and(fTrue, var1, fTrue, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.and(fTrue, var1, var2, fTrue, var1)).isEqualTo(bmgr.and(var1, var2));
}
@Test
public void simplifiedOr() {
BooleanFormula fTrue = bmgr.makeTrue();
BooleanFormula fFalse = bmgr.makeFalse();
BooleanFormula var1 = bmgr.makeVariable("var1");
BooleanFormula var2 = bmgr.makeVariable("var2");
Truth.assertThat(bmgr.or(fTrue, fTrue)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.or(fTrue, fFalse)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fTrue, var1)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fFalse, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.or(var1, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.or(fFalse, fTrue, fFalse, fTrue)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fFalse, fFalse, fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.or(fFalse, fTrue, fFalse, fFalse)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fFalse, fTrue, fFalse, var1)).isEqualTo(fTrue);
Truth.assertThat(bmgr.or(fFalse, fFalse, fFalse, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.or(fFalse, var1, fFalse, var1)).isEqualTo(var1);
Truth.assertThat(bmgr.or(fFalse, var1, var2, fFalse, var1)).isEqualTo(bmgr.or(var1, var2));
}
@Test
public void simplifiedIfThenElse() {
BooleanFormula fTrue = bmgr.makeTrue();
BooleanFormula fFalse = bmgr.makeFalse();
BooleanFormula var1 = bmgr.makeVariable("var1");
BooleanFormula var2 = bmgr.makeVariable("var2");
Truth.assertThat(bmgr.ifThenElse(fTrue, var1, var2)).isEqualTo(var1);
Truth.assertThat(bmgr.ifThenElse(fFalse, var1, var2)).isEqualTo(var2);
Truth.assertThat(bmgr.ifThenElse(var1, var2, var2)).isEqualTo(var2);
Truth.assertThat(bmgr.ifThenElse(var1, fTrue, fTrue)).isEqualTo(fTrue);
Truth.assertThat(bmgr.ifThenElse(var1, fFalse, fFalse)).isEqualTo(fFalse);
Truth.assertThat(bmgr.ifThenElse(var1, fTrue, fFalse)).isEqualTo(var1);
Truth.assertThat(bmgr.ifThenElse(var1, fFalse, fTrue)).isEqualTo(bmgr.not(var1));
}
}
| 16,278 | 39.799499 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/BooleanFormulaSubject.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assert_;
import com.google.common.base.Joiner;
import com.google.common.truth.Fact;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.SimpleSubjectBuilder;
import com.google.common.truth.StandardSubjectBuilder;
import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.List;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.Model.ValueAssignment;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
/**
* {@link Subject} subclass for testing assertions about BooleanFormulas with Truth (allows using
* <code>assert_().about(...).that(formula).isUnsatisfiable()</code> etc.).
*
* <p>For a test use either {@link SolverBasedTest0#assertThatFormula(BooleanFormula)}, or use
* {@link StandardSubjectBuilder#about(com.google.common.truth.Subject.Factory)} and set a solver
* via the method {@link #booleanFormulasOf(SolverContext)}.
*/
@SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS")
public final class BooleanFormulaSubject extends Subject {
private final SolverContext context;
private final BooleanFormula formulaUnderTest;
private BooleanFormulaSubject(
FailureMetadata pMetadata, BooleanFormula pFormula, SolverContext pMgr) {
super(pMetadata, pFormula);
context = checkNotNull(pMgr);
formulaUnderTest = checkNotNull(pFormula);
}
/**
* Use this for checking assertions about BooleanFormulas (given the corresponding solver) with
* Truth: <code>assert_().about(booleanFormulasOf(context)).that(formula).is...()</code>.
*/
public static Subject.Factory<BooleanFormulaSubject, BooleanFormula> booleanFormulasOf(
final SolverContext context) {
return (metadata, formula) -> new BooleanFormulaSubject(metadata, formula, context);
}
/**
* Use this for checking assertions about BooleanFormulas (given the corresponding solver) with
* Truth: <code>assertUsing(context)).that(formula).is...()</code>.
*/
public static SimpleSubjectBuilder<BooleanFormulaSubject, BooleanFormula> assertUsing(
final SolverContext context) {
return assert_().about(booleanFormulasOf(context));
}
private void checkIsUnsat(final BooleanFormula subject, final Fact expected)
throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(subject);
if (prover.isUnsat()) {
return; // success
}
// get model for failure message
try (Model model = prover.getModel()) {
List<Fact> facts = new ArrayList<>();
facts.add(Fact.fact("but was", formulaUnderTest));
if (!subject.equals(formulaUnderTest)) {
facts.add(Fact.fact("checked formula was", subject));
}
facts.add(Fact.fact("which has model", model));
failWithoutActual(expected, facts.toArray(new Fact[0]));
}
}
}
/**
* Check that the subject is unsatisfiable. Will show a model (satisfying assignment) on failure.
*/
public void isUnsatisfiable() throws SolverException, InterruptedException {
if (context.getFormulaManager().getBooleanFormulaManager().isTrue(formulaUnderTest)) {
failWithoutActual(
Fact.fact("expected to be", "unsatisfiable"),
Fact.fact("but was", "trivially satisfiable"));
return;
}
checkIsUnsat(formulaUnderTest, Fact.simpleFact("expected to be unsatisfiable"));
}
/** Check that the subject is satisfiable. Will show an unsat core on failure. */
public void isSatisfiable() throws SolverException, InterruptedException {
final BooleanFormulaManager bmgr = context.getFormulaManager().getBooleanFormulaManager();
if (bmgr.isFalse(formulaUnderTest)) {
failWithoutActual(
Fact.fact("expected to be", "satisfiable"),
Fact.fact("but was", "trivially unsatisfiable"));
return;
}
try (ProverEnvironment prover = context.newProverEnvironment()) {
prover.push(formulaUnderTest);
if (!prover.isUnsat()) {
return; // success
}
}
reportUnsatCoreForUnexpectedUnsatisfiableFormula();
}
/**
* Check that the subject is satisfiable and provides a model for iteration.
*
* <p>Will show an unsat core on failure.
*/
@SuppressWarnings({"unused", "resource"})
void isSatisfiableAndHasModel(int maxSizeOfModel) throws SolverException, InterruptedException {
final BooleanFormulaManager bmgr = context.getFormulaManager().getBooleanFormulaManager();
if (bmgr.isFalse(formulaUnderTest)) {
failWithoutActual(
Fact.fact("expected to be", "satisfiable"),
Fact.fact("but was", "trivially unsatisfiable"));
return;
}
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(formulaUnderTest);
if (!prover.isUnsat()) {
// check whether the model exists and we can iterate over it.
// We allow an empty model, but it must be available.
try (Model m = prover.getModel()) {
for (ValueAssignment v : m) {
// ignore, we just check iteration
}
}
@SuppressWarnings("unused")
List<ValueAssignment> lst = prover.getModelAssignments();
Truth.assertThat(lst.size()).isAtMost(maxSizeOfModel);
return; // success
}
}
reportUnsatCoreForUnexpectedUnsatisfiableFormula();
}
private void reportUnsatCoreForUnexpectedUnsatisfiableFormula()
throws InterruptedException, SolverException, AssertionError {
try (ProverEnvironment prover =
context.newProverEnvironment(ProverOptions.GENERATE_UNSAT_CORE)) {
// Try to report unsat core for failure message if the solver supports it.
for (BooleanFormula part :
context
.getFormulaManager()
.getBooleanFormulaManager()
.toConjunctionArgs(formulaUnderTest, true)) {
prover.push(part);
}
if (!prover.isUnsat()) {
throw new AssertionError("repated satisfiability check returned different result");
}
final List<BooleanFormula> unsatCore = prover.getUnsatCore();
if (unsatCore.isEmpty()
|| (unsatCore.size() == 1 && formulaUnderTest.equals(unsatCore.get(0)))) {
// empty or trivial unsat core
failWithActual(Fact.fact("expected to be", "satisfiable"));
} else {
failWithoutActual(
Fact.fact("expected to be", "satisfiable"),
Fact.fact("but was", formulaUnderTest),
Fact.fact("which has unsat core", Joiner.on('\n').join(unsatCore)));
}
} catch (UnsupportedOperationException ex) {
// Otherwise just fail (unsat core not supported)
failWithActual(Fact.fact("expected to be", "satisfiable"));
}
}
/**
* Check that the subject is tautological, i.e., always holds. This is equivalent to calling
* {@link #isEquivalentTo(BooleanFormula)} with the formula {@code true}, but it checks
* satisfiability of the subject and unsatisfiability of the negated subject in two steps to
* improve error messages.
*/
public void isTautological() throws SolverException, InterruptedException {
if (context.getFormulaManager().getBooleanFormulaManager().isFalse(formulaUnderTest)) {
failWithoutActual(
Fact.fact("expected to be", "tautological"),
Fact.fact("but was", "trivially unsatisfiable"));
return;
}
checkIsUnsat(
context.getFormulaManager().getBooleanFormulaManager().not(formulaUnderTest),
Fact.fact("expected to be", "tautological"));
}
/**
* Check that the subject is equivalent to a given formula, i.e. {@code subject <=> expected}
* always holds. Will show a counterexample on failure.
*/
public void isEquivalentTo(final BooleanFormula expected)
throws SolverException, InterruptedException {
if (formulaUnderTest.equals(expected)) {
return;
}
final BooleanFormula f =
context.getFormulaManager().getBooleanFormulaManager().xor(formulaUnderTest, expected);
checkIsUnsat(f, Fact.fact("expected to be equivalent to", expected));
}
public void isEquisatisfiableTo(BooleanFormula other)
throws SolverException, InterruptedException {
BooleanFormulaManager bfmgr = context.getFormulaManager().getBooleanFormulaManager();
checkIsUnsat(
bfmgr.and(formulaUnderTest, bfmgr.not(other)),
Fact.fact("expected to be equisatisfiable with", other));
}
/**
* Check that the subject implies a given formula, i.e. {@code subject => expected} always holds.
* Will show a counterexample on failure.
*/
public void implies(final BooleanFormula expected) throws SolverException, InterruptedException {
if (formulaUnderTest.equals(expected)) {
return;
}
final BooleanFormulaManager bmgr = context.getFormulaManager().getBooleanFormulaManager();
final BooleanFormula implication = bmgr.or(bmgr.not(formulaUnderTest), expected);
checkIsUnsat(bmgr.not(implication), Fact.fact("expected to imply", expected));
}
}
| 9,890 | 38.094862 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/BooleanFormulaSubjectTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.ExpectFailure.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.test.BooleanFormulaSubject.booleanFormulasOf;
import com.google.common.base.Throwables;
import com.google.common.truth.ExpectFailure;
import com.google.common.truth.ExpectFailure.SimpleSubjectBuilderCallback;
import com.google.common.truth.SimpleSubjectBuilder;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.SolverException;
/**
* Uses bitvector theory if there is no integer theory available. Notice: Boolector does not support
* bitvectors length 1.
*/
public class BooleanFormulaSubjectTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private BooleanFormula simpleFormula;
private BooleanFormula contradiction;
private BooleanFormula tautology;
@Before
public void setupFormulas() {
if (imgr != null) {
simpleFormula = imgr.equal(imgr.makeVariable("a"), imgr.makeNumber(1));
contradiction =
bmgr.and(simpleFormula, imgr.equal(imgr.makeVariable("a"), imgr.makeNumber(2)));
} else {
simpleFormula = bvmgr.equal(bvmgr.makeVariable(2, "a"), bvmgr.makeBitvector(2, 1));
contradiction =
bmgr.and(
simpleFormula, bvmgr.equal(bvmgr.makeVariable(2, "a"), bvmgr.makeBitvector(2, 2)));
}
tautology = bmgr.or(simpleFormula, bmgr.not(simpleFormula));
}
@Test
public void testIsTriviallySatisfiableYes() throws SolverException, InterruptedException {
assertThatFormula(bmgr.makeTrue()).isSatisfiable();
}
@Test
public void testIsTriviallySatisfiableNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(bmgr.makeFalse()).isSatisfiable());
assertThat(failure).factValue("but was").isEqualTo("trivially unsatisfiable");
}
@Test
public void testIsSatisfiableYes() throws SolverException, InterruptedException {
assertThatFormula(simpleFormula).isSatisfiable();
}
@Test
public void testIsSatisfiableNo() {
assume()
.withMessage("Solver does not support unsat core generation in a usable way")
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(contradiction).isSatisfiable());
assertThat(failure).factValue("which has unsat core").isNotEmpty();
}
@Test
public void testIsTriviallyUnSatisfiableYes() throws SolverException, InterruptedException {
assertThatFormula(bmgr.makeFalse()).isUnsatisfiable();
}
@Test
public void testIsTriviallyUnSatisfiableNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(bmgr.makeTrue()).isUnsatisfiable());
assertThat(failure).factValue("but was").isEqualTo("trivially satisfiable");
}
@Test
public void testIsUnsatisfiableYes() throws SolverException, InterruptedException {
assertThatFormula(contradiction).isUnsatisfiable();
}
@Test
public void testIsUnsatisfiableNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(simpleFormula).isUnsatisfiable());
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
@Test
public void testIsTriviallyTautologicalYes() throws SolverException, InterruptedException {
assertThatFormula(bmgr.makeTrue()).isTautological();
}
@Test
public void testIsTriviallyTautologicalNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(bmgr.makeFalse()).isTautological());
assertThat(failure).factValue("but was").isEqualTo("trivially unsatisfiable");
}
@Test
public void testIsTautologicalYes() throws SolverException, InterruptedException {
assertThatFormula(tautology).isTautological();
}
@Test
public void testIsTautologicalNo1() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(simpleFormula).isTautological());
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
@Test
public void testIsTautologicalNo2() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(contradiction).isTautological());
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
@Test
public void testIsEquivalentToYes() throws SolverException, InterruptedException {
BooleanFormula simpleFormula2;
if (imgr != null) {
simpleFormula2 =
imgr.equal(imgr.makeVariable("a"), imgr.add(imgr.makeNumber(0), imgr.makeNumber(1)));
} else {
simpleFormula2 =
bvmgr.equal(
bvmgr.makeVariable(2, "a"),
bvmgr.add(bvmgr.makeBitvector(2, 0), bvmgr.makeBitvector(2, 1)));
}
assertThatFormula(simpleFormula).isEquivalentTo(simpleFormula2);
}
@Test
public void testIsEquivalentToNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(simpleFormula).isEquivalentTo(tautology));
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
@Test
public void testIsEquisatisfiableToYes() throws SolverException, InterruptedException {
assertThatFormula(simpleFormula).isEquisatisfiableTo(tautology);
}
@Test
public void testIsEquisatisfiableoNo() {
BooleanFormula simpleFormula2;
if (imgr != null) {
simpleFormula2 = imgr.equal(imgr.makeVariable("a"), imgr.makeVariable("2"));
} else {
simpleFormula2 = bvmgr.equal(bvmgr.makeVariable(2, "a"), bvmgr.makeVariable(2, "2"));
}
AssertionError failure =
expectFailure(
whenTesting -> whenTesting.that(simpleFormula).isEquisatisfiableTo(simpleFormula2));
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
@Test
public void testImpliesYes() throws SolverException, InterruptedException {
assertThatFormula(simpleFormula).implies(tautology);
}
@Test
public void testImpliesNo() {
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(tautology).implies(simpleFormula));
requireModel();
assertThat(failure).factValue("which has model").isNotEmpty();
}
private AssertionError expectFailure(ExpectFailureCallback expectFailureCallback) {
return ExpectFailure.expectFailureAbout(booleanFormulasOf(context), expectFailureCallback);
}
/** Variant of {@link SimpleSubjectBuilderCallback} that allows checked exception. */
private interface ExpectFailureCallback
extends SimpleSubjectBuilderCallback<BooleanFormulaSubject, BooleanFormula> {
void invokeAssertionUnchecked(
SimpleSubjectBuilder<BooleanFormulaSubject, BooleanFormula> pWhenTesting) throws Exception;
@Override
default void invokeAssertion(
SimpleSubjectBuilder<BooleanFormulaSubject, BooleanFormula> pWhenTesting) {
try {
invokeAssertionUnchecked(pWhenTesting);
} catch (Exception e) {
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
}
}
| 7,518 | 33.810185 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/EnumerationFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.EnumerationFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType.EnumerationFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
public class EnumerationFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Before
public void init() {
requireEnumeration();
if (solverToUse() == Solvers.MATHSAT5) {
System.out.println(context.getVersion());
assume()
.withMessage(
"Solver %s in version 5.6.8 does not yet support the theory of enumerations",
solverToUse())
.that(context.getVersion())
.doesNotContain("MathSAT5 version 5.6.8");
}
}
@Test
public void testEnumerationDeclaration() {
Set<String> colors = Sets.newHashSet("Blue", "White");
EnumerationFormulaType colorType = emgr.declareEnumeration("Color", "Blue", "White");
assertEquals("Color", colorType.getName());
assertEquals(colors, colorType.getElements());
Set<String> shapes = Sets.newHashSet("Circle", "Square", "Triangle");
EnumerationFormulaType shapeType = emgr.declareEnumeration("Shape", shapes);
assertEquals("Shape", shapeType.getName());
assertEquals(shapes, shapeType.getElements());
assertThat(colors).isNotEqualTo(shapes);
}
@Test
public void testType() {
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorM", "Blue", "White");
EnumerationFormula blue = emgr.makeConstant("Blue", colorType);
EnumerationFormula varColor = emgr.makeVariable("varColor", colorType);
assertEquals(colorType, mgr.getFormulaType(blue));
assertEquals(colorType, mgr.getFormulaType(varColor));
}
@Test
public void testRepeatedEnumerationDeclaration() {
Set<String> colors = Sets.newHashSet("Blue", "White");
Set<String> otherColors = Sets.newHashSet("Blue", "White", "Red");
EnumerationFormulaType colorType = emgr.declareEnumeration("Color", colors);
// same type again is allowed
EnumerationFormulaType identicalColorType = emgr.declareEnumeration("Color", colors);
assertEquals("Color", identicalColorType.getName());
assertEquals(colors, identicalColorType.getElements());
assertEquals(colorType, identicalColorType);
// distinct type with same name is not allowed
assertThrows(
IllegalArgumentException.class, () -> emgr.declareEnumeration("Color", otherColors));
if (solverToUse() == Solvers.MATHSAT5) {
assertThrows(
IllegalArgumentException.class, () -> emgr.declareEnumeration("SameColor", colors));
} else {
// different type with same elements is allowed
EnumerationFormulaType sameColorType = emgr.declareEnumeration("SameColor", colors);
assertEquals("SameColor", sameColorType.getName());
assertEquals(colors, sameColorType.getElements());
// different type with same elements is allowed
EnumerationFormulaType otherColorType = emgr.declareEnumeration("OtherColor", otherColors);
assertThat(otherColorType.getName()).isEqualTo("OtherColor");
assertThat(otherColorType.getElements()).isEqualTo(otherColors);
}
}
@Test
public void testTooManyDistinctValues() throws SolverException, InterruptedException {
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorA", "Blue", "White");
EnumerationFormula color1 = emgr.makeVariable("first", colorType);
EnumerationFormula color2 = emgr.makeVariable("second", colorType);
EnumerationFormula color3 = emgr.makeVariable("third", colorType);
// there are two colors, so there can be two distinct assignments.
assertThatFormula(bmgr.not(emgr.equivalence(color1, color2))).isSatisfiable();
assertThatFormula(bmgr.not(emgr.equivalence(color2, color3))).isSatisfiable();
assertThatFormula(bmgr.not(emgr.equivalence(color3, color1))).isSatisfiable();
// there are only two colors, so there can not be three distinct assignments.
assertThatFormula(
bmgr.and(
bmgr.not(emgr.equivalence(color1, color2)),
bmgr.not(emgr.equivalence(color2, color3)),
bmgr.not(emgr.equivalence(color3, color1))))
.isUnsatisfiable();
}
@Test
public void testConstants() throws SolverException, InterruptedException {
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorB", "Blue", "White");
EnumerationFormula blue = emgr.makeConstant("Blue", colorType);
EnumerationFormula white = emgr.makeConstant("White", colorType);
EnumerationFormula var = emgr.makeVariable("var", colorType);
assertThatFormula(emgr.equivalence(blue, var)).isSatisfiable();
assertThatFormula(emgr.equivalence(white, var)).isSatisfiable();
assertThatFormula(bmgr.not(emgr.equivalence(blue, var))).isSatisfiable();
assertThatFormula(bmgr.not(emgr.equivalence(white, var))).isSatisfiable();
assertThatFormula(bmgr.not(emgr.equivalence(blue, white))).isSatisfiable();
// there are only two colors, so is no third option.
assertThatFormula(
bmgr.or(bmgr.not(emgr.equivalence(blue, var)), bmgr.not(emgr.equivalence(white, var))))
.isSatisfiable();
assertThatFormula(bmgr.or(emgr.equivalence(blue, var), emgr.equivalence(white, var)))
.isSatisfiable();
assertThatFormula(
bmgr.and(bmgr.not(emgr.equivalence(blue, var)), bmgr.not(emgr.equivalence(white, var))))
.isUnsatisfiable();
assertThatFormula(bmgr.and(emgr.equivalence(blue, var), emgr.equivalence(white, var)))
.isUnsatisfiable();
}
@Test
public void testIncompatibleEnumeration() {
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorC", "Blue", "White");
EnumerationFormulaType shapeType =
emgr.declareEnumeration("ShapeC", "Circle", "Rectangle", "Triangle");
EnumerationFormula blue = emgr.makeConstant("Blue", colorType);
EnumerationFormula varColor = emgr.makeVariable("varColor", colorType);
EnumerationFormula circle = emgr.makeConstant("Circle", shapeType);
EnumerationFormula varShape = emgr.makeVariable("varShape", shapeType);
assertThrows(IllegalArgumentException.class, () -> emgr.equivalence(blue, varShape));
assertThrows(IllegalArgumentException.class, () -> emgr.equivalence(circle, varColor));
assertThrows(IllegalArgumentException.class, () -> emgr.equivalence(varColor, varShape));
assertThrows(IllegalArgumentException.class, () -> emgr.equivalence(blue, circle));
}
@Test
public void testInvalidName() {
assertThrows(IllegalArgumentException.class, () -> emgr.declareEnumeration("true", "X", "Y"));
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorE", "Blue", "White");
assertThrows(IllegalArgumentException.class, () -> emgr.makeVariable("true", colorType));
}
private static class ConstantsVisitor extends DefaultFormulaVisitor<TraversalProcess> {
final Set<String> constants = new HashSet<>();
final Set<FunctionDeclarationKind> functions = new HashSet<>();
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitConstant(Formula f, Object value) {
constants.add((String) value);
return visitDefault(f);
}
@Override
public TraversalProcess visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
functions.add(functionDeclaration.getKind());
return visitDefault(f);
}
}
@Test
public void testVisitor() {
requireVisitor();
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorC", "Blue", "White");
EnumerationFormula blue = emgr.makeConstant("Blue", colorType);
EnumerationFormula varColor = emgr.makeVariable("varColor", colorType);
BooleanFormula eq = emgr.equivalence(blue, varColor);
assertThat(mgr.extractVariables(varColor)).containsExactly("varColor", varColor);
assertThat(mgr.extractVariables(eq)).containsExactly("varColor", varColor);
assertThat(mgr.extractVariablesAndUFs(varColor)).containsExactly("varColor", varColor);
assertThat(mgr.extractVariablesAndUFs(eq)).containsExactly("varColor", varColor);
ConstantsVisitor visitor1 = new ConstantsVisitor();
mgr.visitRecursively(blue, visitor1);
assertThat(visitor1.functions).isEmpty();
assertThat(visitor1.constants).containsExactly("Blue");
ConstantsVisitor visitor2 = new ConstantsVisitor();
mgr.visitRecursively(eq, visitor2);
assertThat(visitor2.functions).containsExactly(FunctionDeclarationKind.EQ);
assertThat(visitor2.constants).containsExactly("Blue");
}
@Test
public void testModel() throws SolverException, InterruptedException {
EnumerationFormulaType colorType = emgr.declareEnumeration("ColorM", "Blue", "White");
EnumerationFormula blue = emgr.makeConstant("Blue", colorType);
EnumerationFormula white = emgr.makeConstant("White", colorType);
EnumerationFormula varColor = emgr.makeVariable("varColor", colorType);
EnumerationFormulaType shapeType =
emgr.declareEnumeration("ShapeM", "Circle", "Reactangle", "Triangle");
EnumerationFormula triangle = emgr.makeConstant("Triangle", shapeType);
EnumerationFormula varShape = emgr.makeVariable("varShape", shapeType);
evaluateInModel(
emgr.equivalence(blue, varColor),
varColor,
Lists.newArrayList("Blue"),
Lists.newArrayList(blue));
evaluateInModel(
bmgr.not(emgr.equivalence(blue, varColor)),
varColor,
Lists.newArrayList("White"),
Lists.newArrayList(white));
evaluateInModel(
bmgr.and(emgr.equivalence(blue, varColor), emgr.equivalence(triangle, varShape)),
varColor,
Lists.newArrayList("Blue"),
Lists.newArrayList(blue));
evaluateInModel(
bmgr.and(emgr.equivalence(blue, varColor), emgr.equivalence(triangle, varShape)),
varShape,
Lists.newArrayList("Triangle"),
Lists.newArrayList(triangle));
}
}
| 11,158 | 40.951128 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ExceptionHandlerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import org.junit.Test;
/** Test that exception handling is set up properly. */
public class ExceptionHandlerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test(expected = Exception.class)
@SuppressWarnings("CheckReturnValue")
public void testErrorHandling() {
// Will exit(1) without an exception handler.
rmgr.makeNumber("not-a-number");
}
}
| 654 | 27.478261 | 90 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/FloatingPointFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.common.rationals.ExtendedRational;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType;
import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.Model.ValueAssignment;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
public class FloatingPointFormulaManagerTest
extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
// numbers are small enough to be precise with single precision
private static final int[] SINGLE_PREC_INTS = new int[] {0, 1, 2, 5, 10, 20, 50, 100, 200, 500};
private static final int NUM_RANDOM_TESTS = 100;
private FloatingPointType singlePrecType;
private FloatingPointType doublePrecType;
private FloatingPointFormula nan;
private FloatingPointFormula posInf;
private FloatingPointFormula negInf;
private FloatingPointFormula zero;
private FloatingPointFormula one;
@Before
public void init() {
requireFloats();
singlePrecType = FormulaType.getSinglePrecisionFloatingPointType();
doublePrecType = FormulaType.getDoublePrecisionFloatingPointType();
nan = fpmgr.makeNaN(singlePrecType);
posInf = fpmgr.makePlusInfinity(singlePrecType);
negInf = fpmgr.makeMinusInfinity(singlePrecType);
zero = fpmgr.makeNumber(0.0, singlePrecType);
one = fpmgr.makeNumber(1.0, singlePrecType);
}
@Test
public void floatingPointType() {
FloatingPointType type = FormulaType.getFloatingPointType(23, 42);
FloatingPointFormula var = fpmgr.makeVariable("x", type);
FloatingPointType result = (FloatingPointType) mgr.getFormulaType(var);
assertWithMessage("exponent size")
.that(result.getExponentSize())
.isEqualTo(type.getExponentSize());
assertWithMessage("mantissa size")
.that(result.getMantissaSize())
.isEqualTo(type.getMantissaSize());
}
@Test
public void negative() throws SolverException, InterruptedException {
for (double d : new double[] {-1, -2, -0.0, Double.NEGATIVE_INFINITY}) {
FloatingPointFormula formula = fpmgr.makeNumber(d, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isTautological();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isUnsatisfiable();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.negate(formula), fpmgr.abs(formula)))
.isTautological();
}
for (double d : new double[] {1, 2, 0.0, Double.POSITIVE_INFINITY}) {
FloatingPointFormula formula = fpmgr.makeNumber(d, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isUnsatisfiable();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(formula, fpmgr.abs(formula))).isTautological();
}
}
@Test
public void parser() throws SolverException, InterruptedException {
for (String s : new String[] {"-1", "-Infinity", "-0", "-0.0", "-0.000"}) {
FloatingPointFormula formula = fpmgr.makeNumber(s, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isTautological();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isUnsatisfiable();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.negate(formula), fpmgr.abs(formula)))
.isTautological();
}
for (String s : new String[] {"1", "Infinity", "0", "0.0", "0.000"}) {
FloatingPointFormula formula = fpmgr.makeNumber(s, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isUnsatisfiable();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(formula, fpmgr.abs(formula))).isTautological();
}
for (String s : new String[] {"+1", "+Infinity", "+0", "+0.0", "+0.000"}) {
FloatingPointFormula formula = fpmgr.makeNumber(s, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isUnsatisfiable();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(formula, fpmgr.abs(formula))).isTautological();
}
// NaN is not positive and not negative.
for (String s : new String[] {"NaN", "-NaN", "+NaN"}) {
FloatingPointFormula formula = fpmgr.makeNumber(s, singlePrecType);
assertThatFormula(fpmgr.isNegative(formula)).isUnsatisfiable();
assertThatFormula(fpmgr.isNegative(fpmgr.negate(formula))).isUnsatisfiable();
}
}
@Test
public void negativeZeroDivision() throws SolverException, InterruptedException {
BooleanFormula formula =
fpmgr.equalWithFPSemantics(
fpmgr.divide(
one, fpmgr.makeNumber(-0.0, singlePrecType), FloatingPointRoundingMode.TOWARD_ZERO),
fpmgr.makeMinusInfinity(singlePrecType));
assertThatFormula(formula).isSatisfiable();
assertThatFormula(bmgr.not(formula)).isUnsatisfiable();
}
@Test
public void nanEqualNanIsUnsat() throws SolverException, InterruptedException {
assertThatFormula(fpmgr.equalWithFPSemantics(nan, nan)).isUnsatisfiable();
}
@Test
public void nanAssignedNanIsTrue() throws SolverException, InterruptedException {
assertThatFormula(fpmgr.assignment(nan, nan)).isTautological();
}
@Test
public void infinityOrdering() throws SolverException, InterruptedException {
BooleanFormula order1 = fpmgr.greaterThan(posInf, zero);
BooleanFormula order2 = fpmgr.greaterThan(zero, negInf);
BooleanFormula order3 = fpmgr.greaterThan(posInf, negInf);
assertThatFormula(bmgr.and(order1, order2, order3)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.max(posInf, zero), posInf)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.max(posInf, negInf), posInf))
.isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.max(negInf, zero), zero)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.min(posInf, zero), zero)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.min(posInf, negInf), negInf))
.isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpmgr.min(negInf, zero), negInf)).isTautological();
}
@Test
public void infinityVariableOrdering() throws SolverException, InterruptedException {
FloatingPointFormula var = fpmgr.makeVariable("x", singlePrecType);
BooleanFormula varIsNan = fpmgr.isNaN(var);
BooleanFormula order1 = fpmgr.greaterOrEquals(posInf, var);
BooleanFormula order2 = fpmgr.lessOrEquals(negInf, var);
assertThatFormula(bmgr.or(varIsNan, bmgr.and(order1, order2))).isTautological();
}
@Test
public void sqrt() throws SolverException, InterruptedException {
for (double d : new double[] {0.25, 1, 2, 4, 9, 15, 1234, 1000000}) {
assertThatFormula(
fpmgr.equalWithFPSemantics(
fpmgr.sqrt(fpmgr.makeNumber(d * d, doublePrecType)),
fpmgr.makeNumber(d, doublePrecType)))
.isTautological();
assertThatFormula(
fpmgr.equalWithFPSemantics(
fpmgr.sqrt(fpmgr.makeNumber(d, doublePrecType)),
fpmgr.makeNumber(Math.sqrt(d), doublePrecType)))
.isTautological();
assertThatFormula(fpmgr.isNaN(fpmgr.sqrt(fpmgr.makeNumber(-d, doublePrecType))))
.isTautological();
}
}
@Test
public void specialValueFunctions() throws SolverException, InterruptedException {
assertThatFormula(fpmgr.isInfinity(posInf)).isTautological();
assertThatFormula(fpmgr.isNormal(posInf)).isUnsatisfiable();
assertThatFormula(fpmgr.isSubnormal(posInf)).isUnsatisfiable();
assertThatFormula(fpmgr.isInfinity(negInf)).isTautological();
assertThatFormula(fpmgr.isNormal(negInf)).isUnsatisfiable();
assertThatFormula(fpmgr.isSubnormal(negInf)).isUnsatisfiable();
assertThatFormula(fpmgr.isNaN(nan)).isTautological();
assertThatFormula(fpmgr.isNormal(nan)).isUnsatisfiable();
assertThatFormula(fpmgr.isSubnormal(nan)).isUnsatisfiable();
assertThatFormula(fpmgr.isZero(zero)).isTautological();
assertThatFormula(fpmgr.isSubnormal(zero)).isUnsatisfiable();
assertThatFormula(fpmgr.isSubnormal(zero)).isUnsatisfiable();
FloatingPointFormula negZero = fpmgr.makeNumber(-0.0, singlePrecType);
assertThatFormula(fpmgr.isZero(negZero)).isTautological();
assertThatFormula(fpmgr.isSubnormal(negZero)).isUnsatisfiable();
assertThatFormula(fpmgr.isSubnormal(negZero)).isUnsatisfiable();
FloatingPointFormula minPosNormalValue = fpmgr.makeNumber(Float.MIN_NORMAL, singlePrecType);
assertThatFormula(fpmgr.isSubnormal(minPosNormalValue)).isUnsatisfiable();
assertThatFormula(fpmgr.isNormal(minPosNormalValue)).isSatisfiable();
assertThatFormula(fpmgr.isZero(minPosNormalValue)).isUnsatisfiable();
}
@Test
public void specialDoubles() throws SolverException, InterruptedException {
assertThatFormula(fpmgr.assignment(fpmgr.makeNumber(Double.NaN, singlePrecType), nan))
.isTautological();
assertThatFormula(
fpmgr.assignment(fpmgr.makeNumber(Double.POSITIVE_INFINITY, singlePrecType), posInf))
.isTautological();
assertThatFormula(
fpmgr.assignment(fpmgr.makeNumber(Double.NEGATIVE_INFINITY, singlePrecType), negInf))
.isTautological();
}
private void checkEqualityOfNumberConstantsFor(double value, FloatingPointType type)
throws SolverException, InterruptedException {
FloatingPointFormula doubleNumber = fpmgr.makeNumber(value, type);
FloatingPointFormula stringNumber = fpmgr.makeNumber(Double.toString(value), type);
FloatingPointFormula bigDecimalNumber = fpmgr.makeNumber(BigDecimal.valueOf(value), type);
FloatingPointFormula rationalNumber =
fpmgr.makeNumber(Rational.ofBigDecimal(BigDecimal.valueOf(value)), type);
BooleanFormula eq1 = fpmgr.equalWithFPSemantics(doubleNumber, stringNumber);
BooleanFormula eq2 = fpmgr.equalWithFPSemantics(doubleNumber, bigDecimalNumber);
BooleanFormula eq3 = fpmgr.equalWithFPSemantics(doubleNumber, rationalNumber);
assertThatFormula(bmgr.and(eq1, eq2, eq3)).isTautological();
}
@Test
@SuppressWarnings("FloatingPointLiteralPrecision")
public void numberConstants() throws SolverException, InterruptedException {
checkEqualityOfNumberConstantsFor(1.0, singlePrecType);
checkEqualityOfNumberConstantsFor(-5.877471754111438E-39, singlePrecType);
checkEqualityOfNumberConstantsFor(-5.877471754111438E-39, doublePrecType);
checkEqualityOfNumberConstantsFor(3.4028234663852886e+38, singlePrecType);
checkEqualityOfNumberConstantsFor(3.4028234663852886e+38, doublePrecType);
// check unequality for large types
FloatingPointType nearDouble = FormulaType.getFloatingPointType(12, 52);
FloatingPointFormula h1 =
fpmgr.makeNumber(BigDecimal.TEN.pow(309).multiply(BigDecimal.valueOf(1.0001)), nearDouble);
FloatingPointFormula h2 =
fpmgr.makeNumber(BigDecimal.TEN.pow(309).multiply(BigDecimal.valueOf(1.0002)), nearDouble);
assertThatFormula(fpmgr.equalWithFPSemantics(h1, h2)).isUnsatisfiable();
// check equality for short types
FloatingPointType smallType = FormulaType.getFloatingPointType(4, 4);
FloatingPointFormula i1 =
fpmgr.makeNumber(BigDecimal.TEN.pow(50).multiply(BigDecimal.valueOf(1.001)), smallType);
FloatingPointFormula i2 =
fpmgr.makeNumber(BigDecimal.TEN.pow(50).multiply(BigDecimal.valueOf(1.002)), smallType);
FloatingPointFormula inf = fpmgr.makePlusInfinity(smallType);
assertThatFormula(fpmgr.equalWithFPSemantics(i1, i2)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(i1, inf)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(i2, inf)).isTautological();
assertThatFormula(fpmgr.isInfinity(i1)).isTautological();
assertThatFormula(fpmgr.isInfinity(i2)).isTautological();
// and some negative numbers
FloatingPointFormula ni1 =
fpmgr.makeNumber(
BigDecimal.TEN.pow(50).multiply(BigDecimal.valueOf(1.001)).negate(), smallType);
FloatingPointFormula ni2 =
fpmgr.makeNumber(
BigDecimal.TEN.pow(50).multiply(BigDecimal.valueOf(1.002)).negate(), smallType);
FloatingPointFormula ninf = fpmgr.makeMinusInfinity(smallType);
assertThatFormula(fpmgr.equalWithFPSemantics(ni1, ni2)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(ni1, ninf)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(ni2, ninf)).isTautological();
assertThatFormula(fpmgr.isInfinity(ni1)).isTautological();
assertThatFormula(fpmgr.isInfinity(ni2)).isTautological();
assertThatFormula(fpmgr.isNegative(ni1)).isTautological();
assertThatFormula(fpmgr.isNegative(ni2)).isTautological();
// check equality for short types
FloatingPointType smallType2 = FormulaType.getFloatingPointType(4, 4);
FloatingPointFormula j1 =
fpmgr.makeNumber(BigDecimal.TEN.pow(500).multiply(BigDecimal.valueOf(1.001)), smallType2);
FloatingPointFormula j2 =
fpmgr.makeNumber(BigDecimal.TEN.pow(500).multiply(BigDecimal.valueOf(1.002)), smallType2);
FloatingPointFormula jnf = fpmgr.makePlusInfinity(smallType);
assertThatFormula(fpmgr.equalWithFPSemantics(j1, j2)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(j1, jnf)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(j2, jnf)).isTautological();
assertThatFormula(fpmgr.isInfinity(j1)).isTautological();
assertThatFormula(fpmgr.isInfinity(j2)).isTautological();
// and some negative numbers
FloatingPointFormula nj1 =
fpmgr.makeNumber(
BigDecimal.TEN.pow(500).multiply(BigDecimal.valueOf(1.001)).negate(), smallType2);
FloatingPointFormula nj2 =
fpmgr.makeNumber(
BigDecimal.TEN.pow(500).multiply(BigDecimal.valueOf(1.002)).negate(), smallType2);
FloatingPointFormula njnf = fpmgr.makeMinusInfinity(smallType);
assertThatFormula(fpmgr.equalWithFPSemantics(nj1, nj2)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(nj1, njnf)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(nj2, njnf)).isTautological();
assertThatFormula(fpmgr.isInfinity(nj1)).isTautological();
assertThatFormula(fpmgr.isInfinity(nj2)).isTautological();
assertThatFormula(fpmgr.isNegative(nj1)).isTautological();
assertThatFormula(fpmgr.isNegative(nj2)).isTautological();
// Z3 supports at least FloatingPointType(15, 112). Larger types seem to be rounded.
if (!ImmutableSet.of(Solvers.Z3, Solvers.CVC4).contains(solver)) {
// check unequality for very large types
FloatingPointType largeType = FormulaType.getFloatingPointType(100, 100);
FloatingPointFormula k1 =
fpmgr.makeNumber(BigDecimal.TEN.pow(200).multiply(BigDecimal.valueOf(1.001)), largeType);
FloatingPointFormula k2 =
fpmgr.makeNumber(BigDecimal.TEN.pow(200).multiply(BigDecimal.valueOf(1.002)), largeType);
assertThatFormula(fpmgr.equalWithFPSemantics(k1, k2)).isUnsatisfiable();
}
}
@Test
public void numberConstantsNearInf() throws SolverException, InterruptedException {
checkNearInf(4, 4, 252); // 2**(2**(4-1)) - max(0,2**(2**(4-1)-2-4))
checkNearInf(5, 4, 254); // 2**(2**(4-1)) - max(0,2**(2**(4-1)-2-5))
checkNearInf(6, 4, 255); // 2**(2**(4-1)) - max(0,2**(2**(4-1)-2-6))
checkNearInf(7, 4, 256); // 2**(2**(4-1)) - max(0,?)
checkNearInf(10, 4, 256); // 2**(2**(4-1)) - max(0,?)
if (Solvers.CVC4 != solverToUse()) {
// It seems as if CVC4/symfpu can not handle numbers with size of mantissa < exponent
// TODO check this!
checkNearInf(4, 5, 64512); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-4))
checkNearInf(4, 6, 4227858432L); // 2**(2**(6-1)) - max(0,2**(2**(6-1)-2-4))
}
checkNearInf(5, 5, 65024); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-5))
checkNearInf(6, 5, 65280); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-6))
checkNearInf(7, 5, 65408); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-7))
checkNearInf(10, 5, 65520); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-10))
checkNearInf(14, 5, 65535); // 2**(2**(5-1)) - max(0,2**(2**(5-1)-2-14))
checkNearInf(15, 5, 65536); // 2**(2**(5-1)) - max(0,?)
checkNearInf(10, 6, 4293918720L); // 2**(2**(6-1)) - max(0,2**(2**(6-1)-2-10))
checkNearInf(16, 6, 4294950912L); // 2**(2**(6-1)) - max(0,2**(2**(6-1)-2-16))
}
private void checkNearInf(int mantissa, int exponent, long value)
throws SolverException, InterruptedException {
FloatingPointType type = FormulaType.getFloatingPointType(exponent, mantissa);
FloatingPointFormula fp1 = fpmgr.makeNumber(BigDecimal.valueOf(value), type);
assertThatFormula(fpmgr.isInfinity(fp1)).isTautological();
FloatingPointFormula fp2 = fpmgr.makeNumber(BigDecimal.valueOf(value - 1), type);
assertThatFormula(fpmgr.isInfinity(fp2)).isUnsatisfiable();
}
@Test
public void numberConstantsNearMinusInf() throws SolverException, InterruptedException {
checkNearMinusInf(4, 4, -252);
checkNearMinusInf(5, 4, -254);
checkNearMinusInf(6, 4, -255);
checkNearMinusInf(7, 4, -256);
checkNearMinusInf(10, 4, -256);
if (Solvers.CVC4 != solverToUse()) {
// It seems as if CVC4/symfpu can not handle numbers with size of mantissa < exponent
// TODO check this!
checkNearMinusInf(4, 5, -64512);
checkNearMinusInf(4, 6, -4227858432L);
}
checkNearMinusInf(5, 5, -65024);
checkNearMinusInf(6, 5, -65280);
checkNearMinusInf(7, 5, -65408);
checkNearMinusInf(10, 5, -65520);
checkNearMinusInf(14, 5, -65535);
checkNearMinusInf(15, 5, -65536);
checkNearMinusInf(10, 6, -4293918720L);
checkNearMinusInf(16, 6, -4294950912L);
}
private void checkNearMinusInf(int mantissa, int exponent, long value)
throws SolverException, InterruptedException {
FloatingPointType type = FormulaType.getFloatingPointType(exponent, mantissa);
FloatingPointFormula fp1 = fpmgr.makeNumber(BigDecimal.valueOf(value), type);
assertThatFormula(fpmgr.isInfinity(fp1)).isTautological();
FloatingPointFormula fp2 = fpmgr.makeNumber(BigDecimal.valueOf(value + 1), type);
assertThatFormula(fpmgr.isInfinity(fp2)).isUnsatisfiable();
}
@Test
@SuppressWarnings("FloatingPointLiteralPrecision")
public void cast() throws SolverException, InterruptedException {
FloatingPointFormula doublePrecNumber = fpmgr.makeNumber(1.5, doublePrecType);
FloatingPointFormula singlePrecNumber = fpmgr.makeNumber(1.5, singlePrecType);
FloatingPointFormula narrowedNumber = fpmgr.castTo(doublePrecNumber, true, singlePrecType);
FloatingPointFormula widenedNumber = fpmgr.castTo(singlePrecNumber, true, doublePrecType);
assertThatFormula(fpmgr.equalWithFPSemantics(narrowedNumber, singlePrecNumber))
.isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(widenedNumber, doublePrecNumber)).isTautological();
FloatingPointFormula doublePrecSmallNumber =
fpmgr.makeNumber(5.877471754111438E-39, doublePrecType);
FloatingPointFormula singlePrecSmallNumber =
fpmgr.makeNumber(5.877471754111438E-39, singlePrecType);
FloatingPointFormula widenedSmallNumber =
fpmgr.castTo(singlePrecSmallNumber, true, doublePrecType);
assertThatFormula(fpmgr.equalWithFPSemantics(widenedSmallNumber, doublePrecSmallNumber))
.isTautological();
}
@Test
public void bvToFpSinglePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
bvToFp(i, singlePrecType);
}
}
@Test
public void bvToFpDoublePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
bvToFp(i, doublePrecType);
}
}
private void bvToFp(int i, FloatingPointType prec) throws SolverException, InterruptedException {
BitvectorFormula bv = bvmgr.makeBitvector(32, i);
FloatingPointFormula fp = fpmgr.makeNumber(i, prec);
FloatingPointFormula signedBvToFp = fpmgr.castFrom(bv, true, prec);
FloatingPointFormula unsignedBvToFp = fpmgr.castFrom(bv, false, prec);
assertThatFormula(fpmgr.equalWithFPSemantics(fp, signedBvToFp)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fp, unsignedBvToFp)).isTautological();
}
/** check whether rounded input is equal to result with rounding-mode. */
private void round0(
double value, double toZero, double pos, double neg, double tiesEven, double tiesAway)
throws SolverException, InterruptedException {
FloatingPointFormula f = fpmgr.makeNumber(value, singlePrecType);
// check types
assertThat(mgr.getFormulaType(fpmgr.round(f, FloatingPointRoundingMode.TOWARD_ZERO)))
.isEqualTo(singlePrecType);
assertThat(mgr.getFormulaType(fpmgr.round(f, FloatingPointRoundingMode.TOWARD_POSITIVE)))
.isEqualTo(singlePrecType);
assertThat(mgr.getFormulaType(fpmgr.round(f, FloatingPointRoundingMode.TOWARD_NEGATIVE)))
.isEqualTo(singlePrecType);
assertThat(mgr.getFormulaType(fpmgr.round(f, FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN)))
.isEqualTo(singlePrecType);
if (solver != Solvers.MATHSAT5) { // Mathsat does not support NEAREST_TIES_AWAY
assertThat(mgr.getFormulaType(fpmgr.round(f, FloatingPointRoundingMode.NEAREST_TIES_AWAY)))
.isEqualTo(singlePrecType);
}
// check values
assertEquals(
fpmgr.makeNumber(toZero, singlePrecType),
fpmgr.round(f, FloatingPointRoundingMode.TOWARD_ZERO));
assertEquals(
fpmgr.makeNumber(pos, singlePrecType),
fpmgr.round(f, FloatingPointRoundingMode.TOWARD_POSITIVE));
assertEquals(
fpmgr.makeNumber(neg, singlePrecType),
fpmgr.round(f, FloatingPointRoundingMode.TOWARD_NEGATIVE));
assertEquals(
fpmgr.makeNumber(tiesEven, singlePrecType),
fpmgr.round(f, FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN));
if (solver != Solvers.MATHSAT5) { // Mathsat does not support NEAREST_TIES_AWAY
assertEquals(
fpmgr.makeNumber(tiesAway, singlePrecType),
fpmgr.round(f, FloatingPointRoundingMode.NEAREST_TIES_AWAY));
}
}
private void assertEquals(FloatingPointFormula f1, FloatingPointFormula f2)
throws SolverException, InterruptedException {
assertThatFormula(fpmgr.equalWithFPSemantics(f1, f2)).isTautological();
}
@Test
public void round() throws SolverException, InterruptedException {
// constants
round0(0, 0, 0, 0, 0, 0);
round0(1, 1, 1, 1, 1, 1);
round0(-1, -1, -1, -1, -1, -1);
// positive odd
round0(1.1, 1, 2, 1, 1, 1);
round0(1.5, 1, 2, 1, 2, 2);
round0(1.9, 1, 2, 1, 2, 2);
// positive even
round0(10.1, 10, 11, 10, 10, 10);
round0(10.5, 10, 11, 10, 10, 11);
round0(10.9, 10, 11, 10, 11, 11);
// negative odd
round0(-1.1, -1, -1, -2, -1, -1);
round0(-1.5, -1, -1, -2, -2, -2);
round0(-1.9, -1, -1, -2, -2, -2);
// negative even
round0(-10.1, -10, -10, -11, -10, -10);
round0(-10.5, -10, -10, -11, -10, -11);
round0(-10.9, -10, -10, -11, -11, -11);
}
@Test
public void bvToFpMinusOne() throws SolverException, InterruptedException {
requireBitvectors();
BitvectorFormula bvOne = bvmgr.makeBitvector(32, -1);
FloatingPointFormula fpOne = fpmgr.makeNumber(-1.0, singlePrecType);
// A 32bit value "-1" when interpreted as unsigned is 2^31 - 1
FloatingPointFormula fpMinInt = fpmgr.makeNumber(Math.pow(2, 32) - 1, singlePrecType);
FloatingPointFormula unsignedBvToFpOne = fpmgr.castFrom(bvOne, false, singlePrecType);
FloatingPointFormula signedBvToFpOne = fpmgr.castFrom(bvOne, true, singlePrecType);
assertThatFormula(fpmgr.equalWithFPSemantics(fpOne, signedBvToFpOne)).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(fpMinInt, unsignedBvToFpOne)).isTautological();
}
@Test
public void fpToBvSimpleNumbersSinglePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
fpToBv(i, singlePrecType);
}
}
@Test
public void fpToBvSimpleNegativeNumbersSinglePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
fpToBv(-i, singlePrecType);
}
}
@Test
public void fpToBvSimpleNumbersDoublePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
fpToBv(i, doublePrecType);
}
}
@Test
public void fpToBvSimpleNegativeNumbersDoublePrec() throws SolverException, InterruptedException {
requireBitvectors();
for (int i : SINGLE_PREC_INTS) {
fpToBv(-i, doublePrecType);
}
}
private void fpToBv(int i, FloatingPointType prec) throws SolverException, InterruptedException {
BitvectorFormula bv = bvmgr.makeBitvector(prec.getTotalSize(), i);
FloatingPointFormula fp = fpmgr.makeNumber(i, prec);
BitvectorFormula fpToBv =
fpmgr.castTo(fp, true, FormulaType.getBitvectorTypeWithSize(prec.getTotalSize()));
assertThatFormula(bvmgr.equal(bv, fpToBv)).isTautological();
}
@Test
public void rationalToFpOne() throws SolverException, InterruptedException {
requireRationals();
NumeralFormula ratOne = rmgr.makeNumber(1);
FloatingPointFormula fpOne = fpmgr.makeNumber(1.0, singlePrecType);
FloatingPointFormula ratToFpOne = fpmgr.castFrom(ratOne, true, singlePrecType);
FloatingPointFormula unsignedRatToFpOne = fpmgr.castFrom(ratOne, false, singlePrecType);
assertThat(unsignedRatToFpOne).isEqualTo(ratToFpOne);
assertThatFormula(fpmgr.equalWithFPSemantics(fpOne, ratToFpOne)).isSatisfiable();
}
@Test
public void rationalToFpMinusOne() throws SolverException, InterruptedException {
requireBitvectors();
NumeralFormula ratOne = rmgr.makeNumber(-1);
FloatingPointFormula fpOne = fpmgr.makeNumber(-1.0, singlePrecType);
FloatingPointFormula ratToFpOne = fpmgr.castFrom(ratOne, true, singlePrecType);
FloatingPointFormula unsignedRatToFpOne = fpmgr.castFrom(ratOne, false, singlePrecType);
assertThat(unsignedRatToFpOne).isEqualTo(ratToFpOne);
assertThatFormula(fpmgr.equalWithFPSemantics(fpOne, ratToFpOne)).isSatisfiable();
}
@Test
public void fpToRationalOne() throws SolverException, InterruptedException {
requireRationals();
NumeralFormula ratOne = rmgr.makeNumber(1);
FloatingPointFormula fpOne = fpmgr.makeNumber(1.0, singlePrecType);
NumeralFormula fpToRatOne = fpmgr.castTo(fpOne, true, FormulaType.RationalType);
assertThatFormula(rmgr.equal(ratOne, fpToRatOne)).isSatisfiable();
}
@Test
public void fpToRationalMinusOne() throws SolverException, InterruptedException {
requireRationals();
NumeralFormula ratOne = rmgr.makeNumber(-1);
FloatingPointFormula fpOne = fpmgr.makeNumber(-1.0, singlePrecType);
NumeralFormula fpToRatOne = fpmgr.castTo(fpOne, true, FormulaType.RationalType);
assertThatFormula(rmgr.equal(ratOne, fpToRatOne)).isSatisfiable();
}
@Test
public void fpTraversal() {
assertThat(mgr.extractVariables(zero)).isEmpty();
assertThat(mgr.extractVariablesAndUFs(zero)).isEmpty();
assertThat(mgr.extractVariables(one)).isEmpty();
assertThat(mgr.extractVariablesAndUFs(one)).isEmpty();
assertThat(mgr.extractVariables(posInf)).isEmpty();
assertThat(mgr.extractVariablesAndUFs(posInf)).isEmpty();
assertThat(mgr.extractVariables(nan)).isEmpty();
assertThat(mgr.extractVariablesAndUFs(nan)).isEmpty();
FloatingPointFormula var = fpmgr.makeVariable("x", singlePrecType);
assertThat(mgr.extractVariables(var)).containsExactly("x", var);
assertThat(mgr.extractVariablesAndUFs(var)).containsExactly("x", var);
}
@Test
public void fpTraversalWithRoundingMode() {
FloatingPointFormula two = fpmgr.makeNumber(2.0, singlePrecType);
FloatingPointFormula var = fpmgr.makeVariable("x", singlePrecType);
FloatingPointFormula mult = fpmgr.multiply(two, var);
assertThat(mgr.extractVariables(mult)).containsExactly("x", var);
assertThat(mgr.extractVariablesAndUFs(mult)).containsExactly("x", var);
}
@Test
public void fpIeeeConversionTypes() {
assume()
.withMessage("FP-to-BV conversion not available for CVC4 and CVC5")
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5);
FloatingPointFormula var = fpmgr.makeVariable("var", singlePrecType);
assertThat(mgr.getFormulaType(fpmgr.toIeeeBitvector(var)))
.isEqualTo(FormulaType.getBitvectorTypeWithSize(32));
}
@Test
public void fpIeeeConversion() throws SolverException, InterruptedException {
assume()
.withMessage("FP-to-BV conversion not available for CVC4 and CVC5")
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5);
FloatingPointFormula var = fpmgr.makeVariable("var", singlePrecType);
assertThatFormula(
fpmgr.assignment(
var, fpmgr.fromIeeeBitvector(fpmgr.toIeeeBitvector(var), singlePrecType)))
.isTautological();
}
@Test
public void ieeeFpConversion() throws SolverException, InterruptedException {
assume()
.withMessage("FP-to-BV conversion not available for CVC4 and CVC5")
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5);
BitvectorFormula var = bvmgr.makeBitvector(32, 123456789);
assertThatFormula(
bvmgr.equal(var, fpmgr.toIeeeBitvector(fpmgr.fromIeeeBitvector(var, singlePrecType))))
.isTautological();
}
@Test
public void checkIeeeFpConversion32() throws SolverException, InterruptedException {
for (float f : getListOfFloats()) {
checkFP(
singlePrecType,
bvmgr.makeBitvector(32, Float.floatToRawIntBits(f)),
fpmgr.makeNumber(f, singlePrecType));
}
}
@Test
public void checkIeeeFpConversion64() throws SolverException, InterruptedException {
for (double d : getListOfDoubles()) {
checkFP(
doublePrecType,
bvmgr.makeBitvector(64, Double.doubleToRawLongBits(d)),
fpmgr.makeNumber(d, doublePrecType));
}
}
private List<Float> getListOfFloats() {
List<Float> flts =
Lists.newArrayList(
// Float.NaN, // NaN is no unique bitvector
Float.MIN_NORMAL,
Float.MIN_VALUE,
Float.MAX_VALUE,
Float.POSITIVE_INFINITY,
Float.NEGATIVE_INFINITY,
0.0f // , -0.0f // MathSat5 fails for NEGATIVE_ZERO
);
for (int i = 1; i < 20; i++) {
for (int j = 1; j < 20; j++) {
flts.add((float) (i * Math.pow(10, j)));
}
}
Random rand = new Random(0);
for (int i = 0; i < NUM_RANDOM_TESTS; i++) {
float flt = Float.intBitsToFloat(rand.nextInt());
if (!Float.isNaN(flt)) {
flts.add(flt);
}
}
return flts;
}
private List<Double> getListOfDoubles() {
List<Double> dbls =
Lists.newArrayList(
// Double.NaN, // NaN is no unique bitvector
Double.MIN_NORMAL,
Double.MIN_VALUE,
Double.MAX_VALUE,
Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY,
0.0 // , -0.0 // MathSat5 fails for NEGATIVE_ZERO
);
for (int i = 1; i < 20; i++) {
for (int j = 1; j < 20; j++) {
dbls.add(i * Math.pow(10, j));
}
}
Random rand = new Random(0);
for (int i = 0; i < NUM_RANDOM_TESTS; i++) {
double d = Double.longBitsToDouble(rand.nextLong());
if (!Double.isNaN(d)) {
dbls.add(d);
}
}
return dbls;
}
private void checkFP(FloatingPointType type, BitvectorFormula bv, FloatingPointFormula flt)
throws SolverException, InterruptedException {
assume()
.withMessage("FP-to-BV conversion not available for CVC4 and CVC5")
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5);
BitvectorFormula var = bvmgr.makeVariable(type.getTotalSize(), "x");
assertThat(mgr.getFormulaType(var)).isEqualTo(mgr.getFormulaType(fpmgr.toIeeeBitvector(flt)));
assertThat(mgr.getFormulaType(flt))
.isEqualTo(mgr.getFormulaType(fpmgr.fromIeeeBitvector(bv, type)));
assertThatFormula(bmgr.and(bvmgr.equal(bv, var), bvmgr.equal(var, fpmgr.toIeeeBitvector(flt))))
.isSatisfiable();
assertThatFormula(bvmgr.equal(bv, fpmgr.toIeeeBitvector(flt))).isTautological();
assertThatFormula(fpmgr.equalWithFPSemantics(flt, fpmgr.fromIeeeBitvector(bv, type)))
.isTautological();
}
@Test
public void fpModelValue() throws SolverException, InterruptedException {
FloatingPointFormula zeroVar = fpmgr.makeVariable("zero", singlePrecType);
BooleanFormula zeroEq = fpmgr.assignment(zeroVar, zero);
FloatingPointFormula oneVar = fpmgr.makeVariable("one", singlePrecType);
BooleanFormula oneEq = fpmgr.assignment(oneVar, one);
FloatingPointFormula nanVar = fpmgr.makeVariable("nan", singlePrecType);
BooleanFormula nanEq = fpmgr.assignment(nanVar, nan);
FloatingPointFormula posInfVar = fpmgr.makeVariable("posInf", singlePrecType);
BooleanFormula posInfEq = fpmgr.assignment(posInfVar, posInf);
FloatingPointFormula negInfVar = fpmgr.makeVariable("negInf", singlePrecType);
BooleanFormula negInfEq = fpmgr.assignment(negInfVar, negInf);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(zeroEq);
prover.push(oneEq);
prover.push(nanEq);
prover.push(posInfEq);
prover.push(negInfEq);
assertThat(prover).isSatisfiable();
try (Model model = prover.getModel()) {
Object zeroValue = model.evaluate(zeroVar);
ValueAssignment zeroAssignment =
new ValueAssignment(zeroVar, zero, zeroEq, "zero", zeroValue, ImmutableList.of());
assertThat(zeroValue)
.isAnyOf(ExtendedRational.ZERO, Rational.ZERO, BigDecimal.ZERO, 0.0, 0.0f);
Object oneValue = model.evaluate(oneVar);
ValueAssignment oneAssignment =
new ValueAssignment(oneVar, one, oneEq, "one", oneValue, ImmutableList.of());
assertThat(oneValue)
.isAnyOf(
new ExtendedRational(Rational.ONE),
BigInteger.ONE,
Rational.ONE,
BigDecimal.ONE,
1.0,
1.0f);
Object nanValue = model.evaluate(nanVar);
ValueAssignment nanAssignment =
new ValueAssignment(nanVar, nan, nanEq, "nan", nanValue, ImmutableList.of());
assertThat(nanValue).isAnyOf(ExtendedRational.NaN, Double.NaN, Float.NaN);
Object posInfValue = model.evaluate(posInfVar);
ValueAssignment posInfAssignment =
new ValueAssignment(
posInfVar, posInf, posInfEq, "posInf", posInfValue, ImmutableList.of());
assertThat(posInfValue)
.isAnyOf(ExtendedRational.INFTY, Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
Object negInfValue = model.evaluate(negInfVar);
ValueAssignment negInfAssignment =
new ValueAssignment(
negInfVar, negInf, negInfEq, "negInf", negInfValue, ImmutableList.of());
assertThat(negInfValue)
.isAnyOf(ExtendedRational.NEG_INFTY, Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
assertThat(model)
.containsExactly(
zeroAssignment, oneAssignment, nanAssignment, posInfAssignment, negInfAssignment);
}
}
}
@Test
@SuppressWarnings({"unchecked", "resource"})
public void fpInterpolation() throws SolverException, InterruptedException {
requireInterpolation();
assume()
.withMessage("MathSAT5 does not support floating-point interpolation")
.that(solver)
.isNotEqualTo(Solvers.MATHSAT5);
FloatingPointFormula var = fpmgr.makeVariable("x", singlePrecType);
BooleanFormula f1 = fpmgr.equalWithFPSemantics(var, zero);
BooleanFormula f2 = bmgr.not(fpmgr.isZero(var));
try (InterpolatingProverEnvironment<Object> prover =
(InterpolatingProverEnvironment<Object>) context.newProverEnvironmentWithInterpolation()) {
Object itpGroup1 = prover.push(f1);
prover.push(f2);
assertThat(prover).isUnsatisfiable();
BooleanFormula itp = prover.getInterpolant(ImmutableList.of(itpGroup1));
assertThatFormula(f1).implies(itp);
assertThatFormula(bmgr.and(itp, f2)).isUnsatisfiable();
}
}
@SuppressWarnings("CheckReturnValue")
@Test(expected = Exception.class)
public void failOnInvalidString() {
fpmgr.makeNumber("a", singlePrecType);
assert_().fail();
}
}
| 38,464 | 40.764387 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/FormulaClassifierTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.example.FormulaClassifier;
public class FormulaClassifierTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private FormulaClassifier classifier;
private static final String VARS =
"(declare-fun x () Int)"
+ "(declare-fun xx () Int)"
+ "(declare-fun y () Real)"
+ "(declare-fun yy () Real)"
+ "(declare-fun arr () (Array Int Int))"
+ "(declare-fun arr2 () (Array Int Int))"
+ "(declare-fun foo (Int) Int)"
+ "(declare-fun bar (Real) Real)";
private static final String BVS =
"(declare-fun bv () (_ BitVec 4))" + "(declare-fun bv2 () (_ BitVec 4))";
@Before
public void init() {
classifier = new FormulaClassifier(context);
}
@Test
public void test_AUFLIA() {
requireParser();
requireQuantifiers(); // TODO SMTInterpol fails when parsing this
String query = VARS + "(assert (exists ((z Int)) (= (select arr x) (foo z))))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("AUFLIA");
}
@Test
public void test_QF_AUFLIA() {
requireParser();
String query = VARS + "(assert (= (select arr x) (foo 0)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_AUFLIA");
}
@Test
public void test_QF_AUFLIRA() {
requireParser();
requireRationals();
String query = VARS + "(assert (= (select arr x) (bar (/ 1 2))))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_AUFLIRA");
}
@Test
public void test_QF_AUFNIRA() {
requireParser();
requireRationals();
String query = VARS + "(assert (= (select arr (* x x)) (bar (/ 1 2))))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_AUFNIRA");
}
@Test
public void test_LIA() {
requireParser();
requireQuantifiers();
String query = VARS + "(assert (exists ((z Int)) (= (+ x 1) 0)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("LIA");
}
@Test
public void test_LRA() {
requireParser();
requireQuantifiers();
requireRationals();
String query = VARS + "(assert (exists ((zz Real)) (= (+ y y) zz)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("LRA");
}
@Test
public void test_ABV() {
requireParser();
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
requireQuantifiers();
requireBitvectors();
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
String query =
VARS + BVS + "(assert (and (exists ((bv2 (_ BitVec 4))) (= bv bv2)) (= arr arr2)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("ABV");
}
@Test
public void test_QF_AUFBV() {
requireParser();
requireBitvectors();
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
String query = VARS + BVS + "(assert (and (= bv bv2) (= arr arr2) (= (foo x) x)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_AUFBV");
}
@Test
public void test_QF_BV() {
requireParser();
requireBitvectors();
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
String query = BVS + "(assert (bvult bv (bvadd bv #x1)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_BV");
}
@Test
public void test_QF_LIA() {
requireParser();
String query = VARS + "(assert (< xx (* x 2)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_LIA");
}
@Test
public void test_QF_LRA() {
requireParser();
String query = VARS + "(assert (< yy y))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_LRA");
}
@Test
public void test_QF_NIA() {
requireParser();
String query = VARS + "(assert (< xx (* x x)))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_NIA");
}
@Test
public void test_QF_NRA() {
requireParser();
String query = VARS + "(assert (< yy (* y y)))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_NRA");
}
@Test
public void test_QF_UF() {
requireParser();
String query = VARS + "(assert (= (foo x) x))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_UF");
}
@Test
public void test_QF_UFBV() {
requireParser();
requireBitvectors();
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
String query = VARS + BVS + "(assert (and (= bv bv2) (= (foo x) x)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_UFBV");
}
@Test
public void test_QF_UFLIA() {
requireParser();
String query = VARS + "(assert (< xx (+ x (foo x))))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_UFLIA");
}
@Test
public void test_QF_UFLRA() {
requireParser();
String query = VARS + "(assert (< yy (bar y)))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_UFLRA");
}
@Test
public void test_QF_UFNRA() {
requireParser();
String query = VARS + "(assert (< (* y yy) (bar y)))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_UFNRA");
}
@Test
public void test_UFLRA() {
requireParser();
requireQuantifiers();
String query = VARS + "(assert (exists ((zz Real)) (< (+ y yy) (bar y))))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("UFLRA");
}
@Test
public void test_UFNRA() {
requireParser();
requireQuantifiers(); // TODO SMTInterpol fails when parsing this
String query = VARS + "(assert (exists ((zz Real)) (< (* y yy) (bar y))))";
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS); // Princess rewrites the formula
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("UFNRA");
}
@Test
public void test_QF_FP() {
requireParser();
requireFloats();
String query = VARS + "(declare-fun a () Float32) (assert (fp.eq a (fp.add RNE a a)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("QF_FP");
}
@Test
public void test_FP() {
requireParser();
requireFloats();
requireQuantifiers();
String query = VARS + "(declare-fun a () Float32) (assert (exists ((zz Real)) (fp.eq a a)))";
classifier.visit(mgr.parse(query));
assertThat(classifier.toString()).isEqualTo("FP");
}
}
| 8,241 | 32.233871 | 97 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/FormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.EqualsTester;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
public class FormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void testEmptySubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
BooleanFormula out = mgr.substitute(input, ImmutableMap.of());
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testNoSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
Map<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
BooleanFormula out =
mgr.substitute(
input,
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e")));
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
}
@Test
public void testSubstitutionTwice() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
ImmutableMap<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
BooleanFormula out2 = mgr.substitute(out, substitution);
assertThatFormula(out2).isEquivalentTo(out);
}
@Test
public void formulaEqualsAndHashCode() {
// Solvers without integers (Boolector) get their own test below
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
FunctionDeclaration<IntegerFormula> fb = fmgr.declareUF("f_b", IntegerType, IntegerType);
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(imgr.makeVariable("int_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
imgr.makeNumber(0.0),
imgr.makeNumber(0L),
imgr.makeNumber(BigInteger.ZERO),
imgr.makeNumber(BigDecimal.ZERO),
imgr.makeNumber("0"))
.addEqualityGroup(
imgr.makeNumber(1.0),
imgr.makeNumber(1L),
imgr.makeNumber(BigInteger.ONE),
imgr.makeNumber(BigDecimal.ONE),
imgr.makeNumber("1"))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")),
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF("f_a", IntegerType, IntegerType),
fmgr.declareUF("f_a", IntegerType, IntegerType))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(0)))
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(1)), fmgr.callUF(fb, imgr.makeNumber(1)))
.testEquals();
}
@Test
public void bitvectorFormulaEqualsAndHashCode() {
// Boolector does not support integers and it is easier to make a new test with bvs
requireBitvectors();
FunctionDeclaration<BitvectorFormula> fb =
fmgr.declareUF(
"f_bv",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(bvmgr.makeVariable(8, "bv_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
bvmgr.makeBitvector(8, 0L),
bvmgr.makeBitvector(8, 0),
bvmgr.makeBitvector(8, BigInteger.ZERO))
.addEqualityGroup(
bvmgr.makeBitvector(8, 1L),
bvmgr.makeBitvector(8, 1),
bvmgr.makeBitvector(8, BigInteger.ONE))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")),
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)),
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, bvmgr.makeBitvector(8, 0)))
.addEqualityGroup(
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)), // why not equal?!
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)))
.testEquals();
}
@Test
public void variableNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors
if (imgr != null) {
BooleanFormula constr =
bmgr.or(
imgr.equal(
imgr.subtract(
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("z")),
imgr.makeNumber(10)),
imgr.makeVariable("y")),
imgr.equal(imgr.makeVariable("xx"), imgr.makeVariable("zz")));
assertThat(mgr.extractVariables(constr).keySet()).containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(constr)).isEqualTo(mgr.extractVariables(constr));
} else {
BooleanFormula bvConstr =
bmgr.or(
bvmgr.equal(
bvmgr.subtract(
bvmgr.add(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "z")),
bvmgr.makeBitvector(8, 10)),
bvmgr.makeVariable(8, "y")),
bvmgr.equal(bvmgr.makeVariable(8, "xx"), bvmgr.makeVariable(8, "zz")));
requireVisitor();
assertThat(mgr.extractVariables(bvConstr).keySet())
.containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(bvConstr)).isEqualTo(mgr.extractVariables(bvConstr));
}
}
@Test
public void ufNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors for constraints
if (imgr != null) {
BooleanFormula constraint =
imgr.equal(
fmgr.declareAndCallUF("uf1", IntegerType, ImmutableList.of(imgr.makeVariable("x"))),
fmgr.declareAndCallUF("uf2", IntegerType, ImmutableList.of(imgr.makeVariable("y"))));
assertThat(mgr.extractVariablesAndUFs(constraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(constraint).keySet()).containsExactly("x", "y");
} else {
BooleanFormula bvConstraint =
bvmgr.equal(
fmgr.declareAndCallUF(
"uf1",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "x"))),
fmgr.declareAndCallUF(
"uf2",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "y"))));
requireVisitor();
assertThat(mgr.extractVariablesAndUFs(bvConstraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(bvConstraint).keySet()).containsExactly("x", "y");
}
}
@Test
public void simplifyIntTest() throws SolverException, InterruptedException {
requireIntegers();
// x=1 && y=x+2 && z=y+3 --> simplified: x=1 && y=3 && z=6
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f =
bmgr.and(
imgr.equal(x, num1),
imgr.equal(y, imgr.add(x, num2)),
imgr.equal(z, imgr.add(y, num3)));
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
@Test
public void simplifyArrayTest() throws SolverException, InterruptedException {
requireIntegers();
requireArrays();
// exists arr : (arr[0]=5 && x=arr[0]) --> simplified: x=5
ArrayFormula<IntegerFormula, IntegerFormula> arr =
amgr.makeArray("arr", FormulaType.getArrayType(IntegerType, IntegerType));
IntegerFormula index = imgr.makeNumber(0);
IntegerFormula value = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
ArrayFormula<IntegerFormula, IntegerFormula> write = amgr.store(arr, index, value);
IntegerFormula read = amgr.select(write, index);
BooleanFormula f = imgr.equal(x, read);
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
}
| 13,910 | 41.671779 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/Fuzzer.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Random;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FormulaManager;
/** Boolean fuzzer, useful for testing. */
class Fuzzer {
private final BooleanFormulaManager bfmgr;
private final UniqueIdGenerator idGenerator;
private BooleanFormula[] vars = new BooleanFormula[0];
private final Random r;
private static final String varNameTemplate = "VAR_";
Fuzzer(FormulaManager pFmgr, Random pRandom) {
bfmgr = pFmgr.getBooleanFormulaManager();
idGenerator = new UniqueIdGenerator();
r = pRandom;
}
public BooleanFormula fuzz(int formulaSize, int maxNoVars) {
vars = new BooleanFormula[maxNoVars];
populateVars();
return recFuzz(formulaSize);
}
public BooleanFormula fuzz(int formulaSize, BooleanFormula... pVars) {
vars = pVars;
return recFuzz(formulaSize);
}
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
private BooleanFormula recFuzz(int formulaSize) {
if (formulaSize == 1) {
// The only combination of size 1.
return getVar();
} else if (formulaSize == 2) {
// The only combination of size 2.
return bfmgr.not(getVar());
} else {
formulaSize -= 1;
int pivot = formulaSize / 2;
switch (r.nextInt(3)) {
case 0:
return bfmgr.or(recFuzz(pivot), recFuzz(formulaSize - pivot));
case 1:
return bfmgr.and(recFuzz(pivot), recFuzz(formulaSize - pivot));
case 2:
return bfmgr.not(recFuzz(formulaSize));
default:
throw new UnsupportedOperationException("Unexpected state");
}
}
}
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
private BooleanFormula getVar() {
return vars[r.nextInt(vars.length)];
}
private void populateVars() {
for (int i = 0; i < vars.length; i++) {
vars[i] = getNewVar();
}
}
private BooleanFormula getNewVar() {
return bfmgr.makeVariable(varNameTemplate + idGenerator.getFreshId());
}
}
| 2,453 | 27.206897 | 74 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/HardBitvectorFormulaGenerator.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.List;
import org.sosy_lab.java_smt.api.BitvectorFormulaManager;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
/** Generator of hard formulas using the theory of bitvectors. */
class HardBitvectorFormulaGenerator {
private final BitvectorFormulaManager bvmgr;
private final BooleanFormulaManager bfmgr;
private static final String CHOICE_PREFIX = "bool@";
private static final String COUNTER_PREFIX = "bv@";
// Set width accordingly
private static final int BITVECTOR_WIDTH = 32;
HardBitvectorFormulaGenerator(BitvectorFormulaManager pBvmgr, BooleanFormulaManager pBfmgr) {
bvmgr = pBvmgr;
bfmgr = pBfmgr;
}
BooleanFormula generate(int n) {
Preconditions.checkArgument(n >= 2);
List<BooleanFormula> clauses = new ArrayList<>();
clauses.add(
bvmgr.equal(
bvmgr.makeVariable(BITVECTOR_WIDTH, COUNTER_PREFIX + 0),
bvmgr.makeBitvector(BITVECTOR_WIDTH, 0)));
int lastIdx = 0;
int expected = 0;
for (int i = 1; i < 2 * n; i += 2) {
BooleanFormula selector = bfmgr.makeVariable(CHOICE_PREFIX + i);
clauses.add(bfmgr.or(mkConstraint(i, 3, selector), mkConstraint(i, 2, bfmgr.not(selector))));
clauses.add(
bfmgr.or(mkConstraint(i + 1, 3, bfmgr.not(selector)), mkConstraint(i + 1, 2, selector)));
lastIdx = i + 1;
expected += 5;
}
clauses.add(
bvmgr.greaterThan(
bvmgr.makeVariable(BITVECTOR_WIDTH, COUNTER_PREFIX + lastIdx),
bvmgr.makeBitvector(BITVECTOR_WIDTH, expected),
false));
return bfmgr.and(clauses);
}
private BooleanFormula mkConstraint(int newIdx, int increment, BooleanFormula selector) {
return bfmgr.and(
selector,
bvmgr.equal(
bvmgr.makeVariable(BITVECTOR_WIDTH, COUNTER_PREFIX + newIdx),
bvmgr.add(
bvmgr.makeVariable(BITVECTOR_WIDTH, COUNTER_PREFIX + (newIdx - 1)),
bvmgr.makeBitvector(BITVECTOR_WIDTH, increment))));
}
}
| 2,421 | 34.617647 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/HardIntegerFormulaGenerator.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.List;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
/** Generator of hard formulas using the theory of integers. */
class HardIntegerFormulaGenerator {
private final IntegerFormulaManager ifmgr;
private final BooleanFormulaManager bfmgr;
private static final String CHOICE_PREFIX = "b@";
private static final String COUNTER_PREFIX = "i@";
HardIntegerFormulaGenerator(IntegerFormulaManager pIfmgr, BooleanFormulaManager pBfmgr) {
ifmgr = pIfmgr;
bfmgr = pBfmgr;
}
BooleanFormula generate(int n) {
Preconditions.checkArgument(n >= 2);
List<BooleanFormula> clauses = new ArrayList<>();
clauses.add(ifmgr.equal(ifmgr.makeVariable(COUNTER_PREFIX + 0), ifmgr.makeNumber(0)));
int lastIdx = 0;
int expected = 0;
for (int i = 1; i < 2 * n; i += 2) {
BooleanFormula selector = bfmgr.makeVariable(CHOICE_PREFIX + i);
clauses.add(bfmgr.or(mkConstraint(i, 3, selector), mkConstraint(i, 2, bfmgr.not(selector))));
clauses.add(
bfmgr.or(mkConstraint(i + 1, 3, bfmgr.not(selector)), mkConstraint(i + 1, 2, selector)));
lastIdx = i + 1;
expected += 5;
}
clauses.add(
ifmgr.greaterThan(
ifmgr.makeVariable(COUNTER_PREFIX + lastIdx), ifmgr.makeNumber(expected)));
return bfmgr.and(clauses);
}
private BooleanFormula mkConstraint(int newIdx, int increment, BooleanFormula selector) {
return bfmgr.and(
selector,
ifmgr.equal(
ifmgr.makeVariable(COUNTER_PREFIX + newIdx),
ifmgr.add(
ifmgr.makeVariable(COUNTER_PREFIX + (newIdx - 1)), ifmgr.makeNumber(increment))));
}
}
| 2,120 | 34.35 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/IntegerTheoryFuzzer.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Random;
import java.util.stream.IntStream;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
/** Fuzzer over the theory of integers. */
class IntegerTheoryFuzzer {
private final IntegerFormulaManager ifmgr;
private IntegerFormula[] vars = new IntegerFormula[0];
private final Random r;
private static final String varNameTemplate = "VAR_";
private int maxConstant;
IntegerTheoryFuzzer(FormulaManager fmgr, Random pR) {
ifmgr = fmgr.getIntegerFormulaManager();
r = pR;
}
public IntegerFormula fuzz(int formulaSize, int pMaxConstant) {
IntegerFormula[] args =
IntStream.range(0, formulaSize)
.mapToObj(i -> ifmgr.makeVariable(varNameTemplate + i))
.toArray(IntegerFormula[]::new);
return fuzz(formulaSize, pMaxConstant, args);
}
public IntegerFormula fuzz(int formulaSize, int pMaxConstant, IntegerFormula... pVars) {
vars = pVars;
maxConstant = pMaxConstant;
return recFuzz(formulaSize);
}
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
private IntegerFormula recFuzz(int pFormulaSize) {
if (pFormulaSize == 1) {
if (r.nextBoolean()) {
return getConstant();
} else {
return getVar();
}
} else if (pFormulaSize == 2) {
return ifmgr.negate(getVar());
} else {
// One token taken by the operator.
pFormulaSize -= 1;
// Pivot \in [1, formulaSize - 1]
int pivot = 1 + r.nextInt(pFormulaSize - 1);
switch (r.nextInt(3)) {
case 0:
return ifmgr.add(recFuzz(pivot), recFuzz(pFormulaSize - pivot));
case 1:
return ifmgr.subtract(recFuzz(pivot), recFuzz(pFormulaSize - pivot));
case 2:
// Multiplication by a constant.
return ifmgr.multiply(getConstant(), recFuzz(pFormulaSize - 1));
default:
throw new UnsupportedOperationException("Unexpected state");
}
}
}
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
private IntegerFormula getConstant() {
return ifmgr.makeNumber((long) r.nextInt(2 * maxConstant) - maxConstant);
}
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
private IntegerFormula getVar() {
return vars[r.nextInt(vars.length)];
}
}
| 2,730 | 29.010989 | 90 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/InterpolatingProverTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
/** This class contains some simple Junit-tests to check the interpolation-API of our solvers. */
@SuppressWarnings({"resource", "LocalVariableName"})
public class InterpolatingProverTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
/** Generate a prover environment depending on the parameter above. */
@SuppressWarnings("unchecked")
private <T> InterpolatingProverEnvironment<T> newEnvironmentForTest() {
requireInterpolation();
return (InterpolatingProverEnvironment<T>) context.newProverEnvironmentWithInterpolation();
}
private static final UniqueIdGenerator index = new UniqueIdGenerator(); // to get different names
@Test
@SuppressWarnings("CheckReturnValue")
public <T> void simpleInterpolation() throws SolverException, InterruptedException {
try (InterpolatingProverEnvironment<T> prover = newEnvironmentForTest()) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f1 = imgr.equal(y, imgr.multiply(imgr.makeNumber(2), x));
BooleanFormula f2 =
imgr.equal(y, imgr.add(imgr.makeNumber(1), imgr.multiply(z, imgr.makeNumber(2))));
prover.push(f1);
T id2 = prover.push(f2);
boolean check = prover.isUnsat();
assertWithMessage("formulas must be contradicting").that(check).isTrue();
prover.getInterpolant(ImmutableList.of(id2));
// we actually only check for a successful execution here, the result is irrelevant.
}
}
@Test
@SuppressWarnings("unchecked")
public <T> void emptyInterpolationGroup() throws SolverException, InterruptedException {
try (InterpolatingProverEnvironment<T> prover = newEnvironmentForTest()) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f1 = imgr.equal(y, imgr.multiply(imgr.makeNumber(2), x));
BooleanFormula f2 =
imgr.equal(y, imgr.add(imgr.makeNumber(1), imgr.multiply(z, imgr.makeNumber(2))));
T id1 = prover.push(f1);
T id2 = prover.push(f2);
assertThat(prover.isUnsat()).isTrue();
BooleanFormula emptyB = prover.getInterpolant(ImmutableList.of(id1, id2));
assertThat(bmgr.isFalse(emptyB)).isTrue();
BooleanFormula emptyA = prover.getInterpolant(ImmutableList.of());
assertThat(bmgr.isTrue(emptyA)).isTrue();
}
}
@Test
public <T> void binaryInterpolation() throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
// build formula: 1 = A = B = C = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula C = imgr.equal(b, c);
BooleanFormula D = imgr.equal(c, zero);
T TA = stack.push(A);
T TB = stack.push(B);
T TC = stack.push(C);
T TD = stack.push(D);
assertThat(stack).isUnsatisfiable();
BooleanFormula itp = stack.getInterpolant(ImmutableList.of());
BooleanFormula itpA = stack.getInterpolant(ImmutableList.of(TA));
BooleanFormula itpAB = stack.getInterpolant(ImmutableList.of(TA, TB));
BooleanFormula itpABC = stack.getInterpolant(ImmutableList.of(TA, TB, TC));
BooleanFormula itpD = stack.getInterpolant(ImmutableList.of(TD));
BooleanFormula itpDC = stack.getInterpolant(ImmutableList.of(TD, TC));
BooleanFormula itpDCB = stack.getInterpolant(ImmutableList.of(TD, TC, TB));
BooleanFormula itpABCD = stack.getInterpolant(ImmutableList.of(TA, TB, TC, TD));
stack.close();
// special cases: start and end of sequence might need special handling in the solver
assertThat(bmgr.makeBoolean(true)).isEqualTo(itp);
assertThat(bmgr.makeBoolean(false)).isEqualTo(itpABCD);
// we check here the stricter properties for sequential interpolants,
// but this simple example should work for all solvers
checkItpSequence(ImmutableList.of(A, B, C, D), ImmutableList.of(itpA, itpAB, itpABC));
checkItpSequence(ImmutableList.of(D, C, B, A), ImmutableList.of(itpD, itpDC, itpDCB));
}
@Test
public <T> void binaryInterpolation1() throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
// build formula: 1 = A = B = C = 0
BooleanFormula A = bmgr.makeBoolean(false);
BooleanFormula B = bmgr.makeBoolean(false);
T TA = stack.push(A);
T TB = stack.push(B);
assertThat(stack).isUnsatisfiable();
BooleanFormula itp0 = stack.getInterpolant(ImmutableList.of());
BooleanFormula itpA = stack.getInterpolant(ImmutableList.of(TA));
BooleanFormula itpB = stack.getInterpolant(ImmutableList.of(TA));
BooleanFormula itpAB = stack.getInterpolant(ImmutableList.of(TA, TB));
stack.close();
// special cases: start and end of sequence might need special handling in the solver
assertThat(bmgr.makeBoolean(true)).isEqualTo(itp0);
assertThat(bmgr.makeBoolean(false)).isEqualTo(itpAB);
// want to see non-determinism in all solvers? try this:
// System.out.println(solver + ": " + itpA);
// we check here the stricter properties for sequential interpolants,
// but this simple example should work for all solvers
checkItpSequence(ImmutableList.of(A, B), ImmutableList.of(itpA));
checkItpSequence(ImmutableList.of(B, A), ImmutableList.of(itpB));
}
@Test
public <T> void binaryBVInterpolation1() throws SolverException, InterruptedException {
requireBitvectors();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
int width = 8;
BitvectorFormula n130 = bvmgr.makeBitvector(width, 130);
BitvectorFormula a = bvmgr.makeVariable(width, "a" + i);
BitvectorFormula b = bvmgr.makeVariable(width, "b" + i);
BitvectorFormula c = bvmgr.makeVariable(width, "c" + i);
// build formula: b = a + 130, b > a, c = b + 130, c > b
BooleanFormula A = bvmgr.equal(b, bvmgr.add(a, n130));
BooleanFormula B = bvmgr.greaterThan(b, a, false);
BooleanFormula C = bvmgr.equal(c, bvmgr.add(b, n130));
BooleanFormula D = bvmgr.greaterThan(c, b, false);
T TA = stack.push(A);
T TB = stack.push(B);
T TC = stack.push(C);
T TD = stack.push(D);
assertThat(stack).isUnsatisfiable();
BooleanFormula itp = stack.getInterpolant(ImmutableList.of());
BooleanFormula itpA = stack.getInterpolant(ImmutableList.of(TA));
BooleanFormula itpAB = stack.getInterpolant(ImmutableList.of(TA, TB));
BooleanFormula itpABC = stack.getInterpolant(ImmutableList.of(TA, TB, TC));
BooleanFormula itpD = stack.getInterpolant(ImmutableList.of(TD));
BooleanFormula itpDC = stack.getInterpolant(ImmutableList.of(TD, TC));
BooleanFormula itpDCB = stack.getInterpolant(ImmutableList.of(TD, TC, TB));
BooleanFormula itpABCD = stack.getInterpolant(ImmutableList.of(TA, TB, TC, TD));
stack.close();
// special cases: start and end of sequence might need special handling in the solver
assertThat(bmgr.makeBoolean(true)).isEqualTo(itp);
assertThat(bmgr.makeBoolean(false)).isEqualTo(itpABCD);
// we check here the stricter properties for sequential interpolants,
// but this simple example should work for all solvers
checkItpSequence(ImmutableList.of(A, B, C, D), ImmutableList.of(itpA, itpAB, itpABC));
checkItpSequence(ImmutableList.of(D, C, B, A), ImmutableList.of(itpD, itpDC, itpDCB));
}
private void requireTreeItp() {
requireInterpolation();
assume()
.withMessage("Solver does not support tree-interpolation.")
.that(solver)
.isAnyOf(Solvers.Z3, Solvers.SMTINTERPOL, Solvers.PRINCESS);
}
@Test
public <T> void sequentialInterpolation() throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
requireIntegers();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
// build formula: 1 = A = B = C = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula C = imgr.equal(b, c);
BooleanFormula D = imgr.equal(c, zero);
T TA = stack.push(A);
T TB = stack.push(B);
T TC = stack.push(C);
T TD = stack.push(D);
assertThat(stack).isUnsatisfiable();
List<BooleanFormula> itps1 = stack.getSeqInterpolants0(ImmutableList.of(TA, TB, TC, TD));
List<BooleanFormula> itps2 = stack.getSeqInterpolants0(ImmutableList.of(TD, TC, TB, TA));
List<BooleanFormula> itps3 = stack.getSeqInterpolants0(ImmutableList.of(TA, TC, TB, TD));
List<BooleanFormula> itps4 =
stack.getSeqInterpolants(
Lists.transform(ImmutableList.of(TA, TA, TA, TB, TC, TD, TD), ImmutableSet::of));
List<BooleanFormula> itps5 =
stack.getSeqInterpolants(
Lists.transform(ImmutableList.of(TA, TA, TB, TC, TD, TA, TD), ImmutableSet::of));
List<BooleanFormula> itps6 =
stack.getSeqInterpolants(
Lists.transform(ImmutableList.of(TB, TC, TD, TA, TA, TA, TD), ImmutableSet::of));
stack.close();
checkItpSequence(ImmutableList.of(A, B, C, D), itps1);
checkItpSequence(ImmutableList.of(D, C, B, A), itps2);
checkItpSequence(ImmutableList.of(A, C, B, D), itps3);
checkItpSequence(ImmutableList.of(A, A, A, B, C, D, D), itps4);
checkItpSequence(ImmutableList.of(A, A, B, C, D, A, D), itps5);
checkItpSequence(ImmutableList.of(B, C, D, A, A, A, D), itps6);
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public <T> void sequentialInterpolationWithoutPartition()
throws SolverException, InterruptedException {
requireIntegers();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
stack.push(imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1)));
assertThat(stack).isUnsatisfiable();
// empty list of partition
stack.getSeqInterpolants(ImmutableList.of());
assert_().fail();
}
@Test
public <T> void sequentialInterpolationWithOnePartition()
throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
requireIntegers();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
// build formula: 1 = A = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, zero);
T TA = stack.push(A);
T TB = stack.push(B);
assertThat(stack).isUnsatisfiable();
// list of one partition
List<T> partition = ImmutableList.of(TA, TB);
List<BooleanFormula> itps = stack.getSeqInterpolants(ImmutableList.of(partition));
assertThat(itps).isEmpty();
}
@SuppressWarnings("unchecked")
@Test
public <T> void sequentialInterpolationWithFewPartitions()
throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
requireIntegers();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
// build formula: 1 = A = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, zero);
T TA = stack.push(A);
T TB = stack.push(B);
assertThat(stack).isUnsatisfiable();
Set<T> partition = ImmutableSet.of(TA, TB);
List<BooleanFormula> itps1 = stack.getSeqInterpolants(ImmutableList.of(partition));
List<BooleanFormula> itps2 = stack.getSeqInterpolants0(ImmutableList.of(TA, TB));
List<BooleanFormula> itps3 = stack.getSeqInterpolants0(ImmutableList.of(TB, TA));
stack.close();
checkItpSequence(ImmutableList.of(bmgr.and(A, B)), itps1);
checkItpSequence(ImmutableList.of(A, B), itps2);
checkItpSequence(ImmutableList.of(B, A), itps3);
}
@Test
public <T> void sequentialBVInterpolation() throws SolverException, InterruptedException {
requireBitvectors();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
int width = 8;
BitvectorFormula zero = bvmgr.makeBitvector(width, 0);
BitvectorFormula one = bvmgr.makeBitvector(width, 1);
BitvectorFormula a = bvmgr.makeVariable(width, "a" + i);
BitvectorFormula b = bvmgr.makeVariable(width, "b" + i);
BitvectorFormula c = bvmgr.makeVariable(width, "c" + i);
// build formula: 1 = A = B = C = 0
BooleanFormula A = bvmgr.equal(one, a);
BooleanFormula B = bvmgr.equal(a, b);
BooleanFormula C = bvmgr.equal(b, c);
BooleanFormula D = bvmgr.equal(c, zero);
T TA = stack.push(A);
T TB = stack.push(B);
T TC = stack.push(C);
T TD = stack.push(D);
assertThat(stack).isUnsatisfiable();
List<BooleanFormula> itps1 = stack.getSeqInterpolants0(ImmutableList.of(TA, TB, TC, TD));
List<BooleanFormula> itps2 = stack.getSeqInterpolants0(ImmutableList.of(TD, TC, TB, TA));
List<BooleanFormula> itps3 = stack.getSeqInterpolants0(ImmutableList.of(TA, TC, TB, TD));
List<BooleanFormula> itps4 =
stack.getSeqInterpolants0(ImmutableList.of(TA, TA, TA, TB, TC, TD, TD));
List<BooleanFormula> itps5 =
stack.getSeqInterpolants0(ImmutableList.of(TA, TA, TB, TC, TD, TA, TD));
List<BooleanFormula> itps6 =
stack.getSeqInterpolants0(ImmutableList.of(TB, TC, TD, TA, TA, TA, TD));
stack.close();
checkItpSequence(ImmutableList.of(A, B, C, D), itps1);
checkItpSequence(ImmutableList.of(D, C, B, A), itps2);
checkItpSequence(ImmutableList.of(A, C, B, D), itps3);
checkItpSequence(ImmutableList.of(A, A, A, B, C, D, D), itps4);
checkItpSequence(ImmutableList.of(A, A, B, C, D, A, D), itps5);
checkItpSequence(ImmutableList.of(B, C, D, A, A, A, D), itps6);
}
@Test
public void treeInterpolation() throws SolverException, InterruptedException {
requireTreeItp();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
IntegerFormula d = imgr.makeVariable("d" + i);
// build formula: 1 = A = B = C = D = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula C = imgr.equal(b, c);
BooleanFormula D = imgr.equal(c, d);
BooleanFormula E = imgr.equal(d, zero);
testTreeInterpolants0(A, B, C, D, E);
testTreeInterpolants0(A, B, C, E, D);
testTreeInterpolants0(A, B, D, C, E);
testTreeInterpolants0(A, B, D, E, C);
testTreeInterpolants0(A, B, E, C, D);
testTreeInterpolants0(A, B, E, D, C);
testTreeInterpolants0(bmgr.not(A), A, A, A, A);
testTreeInterpolants0(bmgr.not(A), A, A, A, B);
testTreeInterpolants0(bmgr.not(A), A, A, B, A);
testTreeInterpolants0(bmgr.not(A), A, B, A, A);
testTreeInterpolants0(bmgr.not(A), A, A, B, B);
testTreeInterpolants0(bmgr.not(A), A, B, B, B);
testTreeInterpolants1(A, B, C, D, E);
testTreeInterpolants1(A, B, C, E, D);
testTreeInterpolants1(A, B, D, C, E);
testTreeInterpolants1(A, B, D, E, C);
testTreeInterpolants1(A, B, E, C, D);
testTreeInterpolants1(A, B, E, D, C);
testTreeInterpolants1(bmgr.not(A), A, A, A, A);
testTreeInterpolants1(bmgr.not(A), A, A, A, B);
testTreeInterpolants1(bmgr.not(A), A, A, B, A);
testTreeInterpolants1(bmgr.not(A), A, B, A, A);
testTreeInterpolants1(bmgr.not(A), A, A, B, B);
testTreeInterpolants1(bmgr.not(A), A, B, B, B);
testTreeInterpolants2(A, B, C, D, E);
testTreeInterpolants2(A, B, C, E, D);
testTreeInterpolants2(A, B, D, C, E);
testTreeInterpolants2(A, B, D, E, C);
testTreeInterpolants2(A, B, E, C, D);
testTreeInterpolants2(A, B, E, D, C);
testTreeInterpolants2(bmgr.not(A), A, A, A, A);
testTreeInterpolants2(bmgr.not(A), A, A, A, B);
testTreeInterpolants2(bmgr.not(A), A, A, B, A);
testTreeInterpolants2(bmgr.not(A), A, B, A, A);
testTreeInterpolants2(bmgr.not(A), A, A, B, B);
testTreeInterpolants2(bmgr.not(A), A, B, B, B);
}
private <T> void testTreeInterpolants0(
BooleanFormula pA, BooleanFormula pB, BooleanFormula pC, BooleanFormula pD, BooleanFormula pE)
throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
T TA = stack.push(pA);
T TB = stack.push(pB);
T TC = stack.push(pC);
T TD = stack.push(pD);
T TE = stack.push(pE);
assertThat(stack).isUnsatisfiable();
// we build a very simple tree:
// A D
// | |
// B E
// | /
// C
List<BooleanFormula> itps =
stack.getTreeInterpolants0(
ImmutableList.of(TA, TB, TD, TE, TC), // post-order
new int[] {0, 0, 2, 2, 0}); // left-most node in current subtree
stack.close();
assertThatFormula(pA).implies(itps.get(0));
assertThatFormula(bmgr.and(itps.get(0), pB)).implies(itps.get(1));
assertThatFormula(pD).implies(itps.get(2));
assertThatFormula(bmgr.and(itps.get(2), pE)).implies(itps.get(3));
assertThatFormula(bmgr.and(itps.get(1), itps.get(3), pC)).implies(bmgr.makeBoolean(false));
}
private <T> void testTreeInterpolants1(
BooleanFormula pA, BooleanFormula pB, BooleanFormula pC, BooleanFormula pD, BooleanFormula pE)
throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
T TA = stack.push(pA);
T TB = stack.push(pB);
T TC = stack.push(pC);
T TD = stack.push(pD);
T TE = stack.push(pE);
assertThat(stack).isUnsatisfiable();
// we build a simple tree:
// ABCD
// \|//
// E
List<BooleanFormula> itps =
stack.getTreeInterpolants0(
ImmutableList.of(TA, TB, TC, TD, TE), // post-order
new int[] {0, 1, 2, 3, 0}); // left-most node in current subtree
stack.close();
assertThatFormula(pA).implies(itps.get(0));
assertThatFormula(pB).implies(itps.get(1));
assertThatFormula(pC).implies(itps.get(2));
assertThatFormula(pD).implies(itps.get(3));
assertThatFormula(bmgr.and(itps.get(0), itps.get(1), itps.get(2), itps.get(3), pE))
.implies(bmgr.makeBoolean(false));
}
private <T> void testTreeInterpolants2(
BooleanFormula pA, BooleanFormula pB, BooleanFormula pC, BooleanFormula pD, BooleanFormula pE)
throws SolverException, InterruptedException {
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
T TA = stack.push(pA);
T TB = stack.push(pB);
T TC = stack.push(pC);
T TD = stack.push(pD);
T TE = stack.push(pE);
assertThat(stack).isUnsatisfiable();
// we build a simple degenerated tree:
// A
// |
// B
// |
// C
// |
// D
// |
// E
List<BooleanFormula> itps =
stack.getTreeInterpolants0(
ImmutableList.of(TA, TB, TC, TD, TE), // post-order
new int[] {0, 0, 0, 0, 0}); // left-most node in current subtree
stack.close();
assertThatFormula(pA).implies(itps.get(0));
assertThatFormula(bmgr.and(itps.get(0), pB)).implies(itps.get(1));
assertThatFormula(bmgr.and(itps.get(1), pC)).implies(itps.get(2));
assertThatFormula(bmgr.and(itps.get(2), pD)).implies(itps.get(3));
assertThatFormula(bmgr.and(itps.get(3), pE)).implies(bmgr.makeBoolean(false));
}
@Test
public <T> void treeInterpolation2() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula five = imgr.makeNumber(5);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
IntegerFormula d = imgr.makeVariable("d" + i);
IntegerFormula e = imgr.makeVariable("e" + i);
// build formula: 1 = A = B = C = D+1 and D = E = 5
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula R1 = imgr.equal(b, c);
BooleanFormula C = imgr.equal(c, imgr.add(d, one));
BooleanFormula R2 = imgr.equal(d, e);
BooleanFormula D = imgr.equal(e, five);
T TA = stack.push(A);
T TB = stack.push(B);
T TC = stack.push(C);
T TD = stack.push(D);
T TR1 = stack.push(R1);
T TR2 = stack.push(R2);
assertThat(stack).isUnsatisfiable();
// we build a simple tree:
// A
// |
// B C
// | /
// R1 D
// | /
// R2
List<BooleanFormula> itps =
stack.getTreeInterpolants0(
ImmutableList.of(TA, TB, TC, TR1, TD, TR2), // post-order
new int[] {0, 0, 2, 0, 4, 0}); // left-most node in current subtree
stack.close();
assertThatFormula(A).implies(itps.get(0));
assertThatFormula(bmgr.and(itps.get(0), B)).implies(itps.get(1));
assertThatFormula(C).implies(itps.get(2));
assertThatFormula(bmgr.and(itps.get(1), itps.get(2), R1)).implies(itps.get(3));
assertThatFormula(D).implies(itps.get(4));
assertThatFormula(bmgr.and(itps.get(3), itps.get(4), R2)).implies(bmgr.makeBoolean(false));
}
@SuppressWarnings("unchecked")
@Test
public <T> void treeInterpolation3() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula five = imgr.makeNumber(5);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
IntegerFormula d = imgr.makeVariable("d" + i);
IntegerFormula e = imgr.makeVariable("e" + i);
// build formula: 1 = A = B = C = D+1 and D = E = 5
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula R1 = imgr.equal(b, c);
BooleanFormula C = imgr.equal(c, imgr.add(d, one));
BooleanFormula R2 = imgr.equal(d, e);
BooleanFormula D = imgr.equal(e, five);
Set<T> TB = ImmutableSet.of(stack.push(A), stack.push(B));
Set<T> TR1 = ImmutableSet.of(stack.push(R1));
Set<T> TC = ImmutableSet.of(stack.push(A), stack.push(C));
Set<T> TR2 = ImmutableSet.of(stack.push(R2));
Set<T> TD = ImmutableSet.of(stack.push(A), stack.push(D));
assertThat(stack).isUnsatisfiable();
// we build a simple tree:
// A+B A+C
// | /
// R1 A+D
// | /
// R2
List<BooleanFormula> itps =
stack.getTreeInterpolants(
ImmutableList.of(TB, TC, TR1, TD, TR2), // post-order
new int[] {0, 1, 0, 3, 0}); // left-most node in current subtree
assertThat(itps).hasSize(4);
stack.close();
assertThatFormula(bmgr.and(A, B)).implies(itps.get(0));
assertThatFormula(bmgr.and(A, C)).implies(itps.get(1));
assertThatFormula(bmgr.and(itps.get(0), itps.get(1), R1)).implies(itps.get(2));
assertThatFormula(bmgr.and(A, D)).implies(itps.get(3));
assertThatFormula(bmgr.and(itps.get(2), itps.get(3), R2)).implies(bmgr.makeBoolean(false));
}
@Test
public <T> void treeInterpolation4() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
// build formula: a=9 & b+c=a & b=1 & c=2
BooleanFormula bEquals1 = imgr.equal(b, imgr.makeNumber(1));
BooleanFormula cEquals2 = imgr.equal(c, imgr.makeNumber(2));
BooleanFormula bPlusCEqualsA = imgr.equal(imgr.add(b, c), a);
BooleanFormula aEquals9 = imgr.equal(a, imgr.makeNumber(9));
T TbEquals1 = stack.push(bEquals1);
T TcEquals2 = stack.push(cEquals2);
T TbPlusCEqualsA = stack.push(bPlusCEqualsA);
T TaEquals9 = stack.push(aEquals9);
assertThat(stack).isUnsatisfiable();
// we build a simple tree:
// b=1 c=2
// | /
// b+c=a
// |
// a=9
List<BooleanFormula> itps =
stack.getTreeInterpolants0(
ImmutableList.of(TbEquals1, TcEquals2, TbPlusCEqualsA, TaEquals9), // post-order
new int[] {0, 1, 0, 0}); // left-most node in current subtree
assertThat(itps).hasSize(3);
stack.close();
assertThatFormula(bEquals1).implies(itps.get(0));
assertThatFormula(cEquals2).implies(itps.get(1));
assertThatFormula(bmgr.and(itps.get(0), itps.get(1), bPlusCEqualsA)).implies(itps.get(2));
assertThatFormula(bmgr.and(itps.get(2), aEquals9)).implies(bmgr.makeBoolean(false));
}
@Test
public <T> void treeInterpolationForSequence() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
// build formula: 1 = A = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, zero);
List<T> formulas = ImmutableList.of(stack.push(A), stack.push(B));
assertThat(stack).isUnsatisfiable();
List<BooleanFormula> itp = stack.getTreeInterpolants0(formulas, new int[] {0, 0});
assertThat(itp).hasSize(1);
}
@Test
public <T> void treeInterpolationBranching() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
IntegerFormula b = imgr.makeVariable("b" + i);
IntegerFormula c = imgr.makeVariable("c" + i);
IntegerFormula d = imgr.makeVariable("d" + i);
IntegerFormula e = imgr.makeVariable("e" + i);
// build formula: 1 = A = B = C = D = E = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, b);
BooleanFormula C = imgr.equal(b, c);
BooleanFormula D = imgr.equal(c, d);
BooleanFormula E = imgr.equal(d, e);
BooleanFormula F = imgr.equal(e, zero);
List<T> formulas =
ImmutableList.of(
stack.push(A),
stack.push(B),
stack.push(C),
stack.push(D),
stack.push(E),
stack.push(F));
assertThat(stack).isUnsatisfiable();
List<BooleanFormula> itp = stack.getTreeInterpolants0(formulas, new int[] {0, 1, 2, 3, 4, 0});
assertThat(itp).hasSize(5);
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings({"unchecked", "varargs", "CheckReturnValue"})
public <T> void treeInterpolationMalFormed1() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
Set<T> TA = ImmutableSet.of(stack.push(A));
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants(ImmutableList.of(TA), new int[] {0, 0});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings({"unchecked", "varargs", "CheckReturnValue"})
public <T> void treeInterpolationMalFormed2() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
Set<T> TA = ImmutableSet.of(stack.push(A));
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants(ImmutableList.of(TA), new int[] {4});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings({"unchecked", "varargs", "CheckReturnValue"})
public <T> void treeInterpolationMalFormed3() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
Set<T> TA = ImmutableSet.of(stack.push(A));
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants(ImmutableList.of(TA, TA), new int[] {1, 0});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public <T> void treeInterpolationMalFormed4() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
T TA = stack.push(A);
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants0(ImmutableList.of(TA, TA, TA), new int[] {0, 1, 1});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public <T> void treeInterpolationMalFormed5() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
T TA = stack.push(A);
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants0(ImmutableList.of(TA, TA, TA), new int[] {0, 1, 2});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public <T> void treeInterpolationMalFormed6() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
BooleanFormula A = imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1));
T TA = stack.push(A);
assertThat(stack).isUnsatisfiable();
stack.getTreeInterpolants0(ImmutableList.of(TA, TA, TA), new int[] {0, 2, 0});
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public <T> void treeInterpolationWithoutPartition() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
stack.push(imgr.equal(imgr.makeNumber(0), imgr.makeNumber(1)));
assertThat(stack).isUnsatisfiable();
// empty list of partition
stack.getTreeInterpolants(ImmutableList.of(), new int[] {});
assert_().fail();
}
@Test
public <T> void treeInterpolationWithOnePartition() throws SolverException, InterruptedException {
requireTreeItp();
InterpolatingProverEnvironment<T> stack = newEnvironmentForTest();
int i = index.getFreshId();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula a = imgr.makeVariable("a" + i);
// build formula: 1 = A = 0
BooleanFormula A = imgr.equal(one, a);
BooleanFormula B = imgr.equal(a, zero);
T TA = stack.push(A);
T TB = stack.push(B);
assertThat(stack).isUnsatisfiable();
// list of one partition
List<T> partition = ImmutableList.of(TA, TB);
List<BooleanFormula> itps =
stack.getTreeInterpolants(ImmutableList.of(partition), new int[] {0});
assertThat(itps).isEmpty();
}
@Test
public <T> void bigSeqInterpolationTest() throws InterruptedException, SolverException {
requireBitvectors();
requireInterpolation();
int bvWidth = 32;
BitvectorFormula bv0 = bvmgr.makeBitvector(bvWidth, 0);
BitvectorFormula bv1 = bvmgr.makeBitvector(bvWidth, 1);
BitvectorFormula bv2 = bvmgr.makeBitvector(bvWidth, 2);
BitvectorFormula bv4 = bvmgr.makeBitvector(bvWidth, 4);
BitvectorFormula bv8 = bvmgr.makeBitvector(bvWidth, 8);
BitvectorFormula t2 = bvmgr.makeVariable(bvWidth, "tmp3");
BitvectorFormula p = bvmgr.makeVariable(bvWidth, "ADDRESS_OF_main::pathbuf");
BitvectorFormula p2 = bvmgr.makeVariable(bvWidth, "glob2::pathbuf2");
BitvectorFormula p3 = bvmgr.makeVariable(bvWidth, "glob2::p3");
BitvectorFormula p4 = bvmgr.makeVariable(bvWidth, "glob2::pathlim2");
BitvectorFormula b = bvmgr.makeVariable(bvWidth, "main::bound2");
BitvectorFormula c = bvmgr.makeVariable(bvWidth, "VERIFIER_assert::cond2");
BooleanFormula f1Internal1 =
bmgr.and(
bvmgr.lessThan(bv0, p, true),
bvmgr.equal(bvmgr.modulo(p, bv4, false), bvmgr.modulo(bv0, bv4, false)),
bvmgr.lessThan(bv0, bvmgr.add(p, bv8), true));
BooleanFormula f1Internal2 =
bvmgr.equal(bvmgr.modulo(p, bv4, false), bvmgr.modulo(bv0, bv4, false));
BooleanFormula f1Internal3 = bvmgr.lessThan(bv0, bvmgr.add(p, bv8), true);
BooleanFormula f1Internal5 =
bvmgr.equal(
b, bvmgr.subtract(bvmgr.add(p, bvmgr.multiply(bv2, bv4)), bvmgr.multiply(bv1, bv4)));
BooleanFormula f1Internal6 =
bvmgr.equal(
t2, bvmgr.subtract(bvmgr.add(p, bvmgr.multiply(bv2, bv4)), bvmgr.multiply(bv1, bv4)));
BooleanFormula f1Internal7 = bvmgr.equal(p2, p);
BooleanFormula f1 =
bmgr.and(
f1Internal1,
f1Internal2,
f1Internal3,
f1Internal5,
f1Internal6,
f1Internal7,
bvmgr.equal(p3, p2));
BooleanFormula f2 =
bmgr.and(
bvmgr.lessOrEquals(p3, p4, true),
bvmgr.equal(c, bmgr.ifThenElse(bvmgr.lessOrEquals(p3, t2, true), bv1, bv0)),
bvmgr.equal(c, bv0));
try (InterpolatingProverEnvironment<T> prover = newEnvironmentForTest()) {
T id1 = prover.push(f2);
T id2 = prover.push(f1);
assertThat(prover).isUnsatisfiable();
@SuppressWarnings("unused")
List<BooleanFormula> interpolants = prover.getSeqInterpolants0(ImmutableList.of(id1, id2));
}
}
private void checkItpSequence(List<BooleanFormula> formulas, List<BooleanFormula> itps)
throws SolverException, InterruptedException {
assertWithMessage(
"there should be N-1 interpolants for N formulas, but we got %s for %s", itps, formulas)
.that(formulas.size() - 1 == itps.size())
.isTrue();
if (!itps.isEmpty()) {
assertThatFormula(formulas.get(0)).implies(itps.get(0));
for (int i = 1; i < formulas.size() - 1; i++) {
assertThatFormula(bmgr.and(itps.get(i - 1), formulas.get(i))).implies(itps.get(i));
}
assertThatFormula(bmgr.and(getLast(itps), getLast(formulas)))
.implies(bmgr.makeBoolean(false));
}
}
}
| 36,610 | 35.428856 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/InterpolatingProverWithAssumptionsWrapperTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;
import org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper.InterpolatingProverWithAssumptionsWrapper;
public class InterpolatingProverWithAssumptionsWrapperTest
extends SolverFormulaWithAssumptionsTest {
@Override
@SuppressWarnings({"unchecked", "rawtypes", "resource"})
protected <T> InterpolatingProverEnvironment<T> newEnvironmentForTest() {
final InterpolatingProverEnvironment<?> proverEnvironment =
context.newProverEnvironmentWithInterpolation();
return new InterpolatingProverWithAssumptionsWrapper(proverEnvironment, mgr);
}
}
| 911 | 35.48 | 104 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ModelEvaluationTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.Test;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Evaluator;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
/** Test that we can request evaluations from models. */
public class ModelEvaluationTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
/**
* This is the default boolean value for unknown model evaluations. For unknown model evaluation
* for variables or formulas, the solver can return NULL or a default value.
*/
private static final boolean DEFAULT_MODEL_BOOLEAN = false;
/**
* This is the default integer value for unknown model evaluations. For unknown model evaluation
* for variables or formulas, the solver can return NULL or a default value.
*/
private static final int DEFAULT_MODEL_INT = 0;
/**
* This is the default String value for unknown model evaluations. For unknown model evaluation
* for variables or formulas, the solver can return NULL or a default value.
*/
private static final String DEFAULT_MODEL_STRING = "";
private static int problemSize;
@Override
protected ConfigurationBuilder createTestConfigBuilder() {
problemSize = solverToUse() == Solvers.PRINCESS ? 10 : 100; // Princess is too slow.
ConfigurationBuilder builder = super.createTestConfigBuilder();
if (solverToUse() == Solvers.MATHSAT5) {
builder.setOption("solver.mathsat5.furtherOptions", "model_generation=true");
}
return builder;
}
@Test
public void testGetSmallIntegersEvaluation1() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("y"), imgr.makeVariable("z")),
Lists.newArrayList(null, BigInteger.valueOf(DEFAULT_MODEL_INT)),
Lists.newArrayList(null, imgr.makeNumber(DEFAULT_MODEL_INT)));
}
@Test
public void testGetSmallIntegersEvaluation2() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("y"), imgr.makeNumber(1)),
Lists.newArrayList(null, BigInteger.ONE),
Lists.newArrayList(null, imgr.makeNumber(1)));
}
@Test
public void testGetNegativeIntegersEvaluation() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(-10)),
imgr.add(imgr.makeVariable("y"), imgr.makeNumber(1)),
Lists.newArrayList(null, BigInteger.ONE),
Lists.newArrayList(null, imgr.makeNumber(1)));
}
@Test
public void testGetSmallIntegralRationalsEvaluation1()
throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.add(rmgr.makeVariable("y"), rmgr.makeVariable("y")),
Lists.newArrayList(null, Rational.of(DEFAULT_MODEL_INT)),
Lists.newArrayList(null, rmgr.makeNumber(DEFAULT_MODEL_INT)));
}
@Test
public void testGetSmallIntegralRationalsEvaluation2()
throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.makeVariable("y"),
Lists.newArrayList(null, Rational.of(DEFAULT_MODEL_INT)),
Lists.newArrayList(null, rmgr.makeNumber(DEFAULT_MODEL_INT)));
}
@Test
public void testGetRationalsEvaluation() throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("1/3"))),
rmgr.divide(rmgr.makeVariable("y"), rmgr.makeNumber(2)),
Lists.newArrayList(null, Rational.of(DEFAULT_MODEL_INT)),
Lists.newArrayList(null, rmgr.makeNumber(DEFAULT_MODEL_INT)));
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("15"))),
rmgr.makeVariable("x"),
Lists.newArrayList(null, Rational.of(15)),
Lists.newArrayList(null, rmgr.makeNumber(15)));
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("15"))),
rmgr.divide(rmgr.makeVariable("x"), rmgr.makeNumber(3)),
Lists.newArrayList(null, Rational.of(5)),
Lists.newArrayList(null, rmgr.makeNumber(5)));
}
@Test
public void testGetBooleansEvaluation() throws SolverException, InterruptedException {
evaluateInModel(
bmgr.makeVariable("x"),
bmgr.makeVariable("y"),
Lists.newArrayList(null, DEFAULT_MODEL_BOOLEAN),
Lists.newArrayList(null, bmgr.makeBoolean(DEFAULT_MODEL_BOOLEAN)));
}
@Test
public void testGetStringsEvaluation() throws SolverException, InterruptedException {
requireStrings();
evaluateInModel(
smgr.equal(smgr.makeVariable("x"), smgr.makeString("hello")),
smgr.makeVariable("y"),
Lists.newArrayList(null, DEFAULT_MODEL_STRING),
Lists.newArrayList(null, smgr.makeString(DEFAULT_MODEL_STRING)));
}
@Test
public void testModelGeneration() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(getConstraints()));
for (int i = 0; i < problemSize; i++) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
prover.push(getNewConstraints(i, m));
}
}
}
}
@Test
public void testEvaluatorGeneration() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(getConstraints()));
for (int i = 0; i < problemSize; i++) {
assertThat(prover).isSatisfiable();
try (Evaluator m = prover.getEvaluator()) {
prover.push(getNewConstraints(i, m));
}
}
}
}
@NonNull
private List<BooleanFormula> getConstraints() {
List<BooleanFormula> constraints = new ArrayList<>();
for (int i = 0; i < problemSize; i++) {
BooleanFormula x = bmgr.makeVariable("x" + i);
for (int j = 0; j < 5; j++) {
BooleanFormula y = bmgr.makeVariable("y" + i + "_" + j);
constraints.add(bmgr.equivalence(x, y));
constraints.add(bmgr.makeVariable("a" + i + "_" + j));
constraints.add(bmgr.makeVariable("b" + i + "_" + j));
constraints.add(bmgr.makeVariable("c" + i + "_" + j));
constraints.add(bmgr.makeVariable("d" + i + "_" + j));
}
}
return constraints;
}
private BooleanFormula getNewConstraints(int i, Evaluator m) {
BooleanFormula x = bmgr.makeVariable("x" + i);
// prover.push(m.evaluate(x) ? bmgr.not(x) : x);
return m.evaluate(x) ? x : bmgr.not(x);
}
}
| 7,818 | 37.517241 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ModelTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FormulaType.BitvectorType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.Model.ValueAssignment;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
/** Test that values from models are appropriately parsed. */
public class ModelTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
// A list of variables to test that model variable names are correctly applied
private static final ImmutableList<String> VARIABLE_NAMES =
ImmutableList.of(
"x",
"x-x",
"x::x",
"@x",
"x@",
"x@x",
"@x@",
"BTOR_1@",
"BTOR_1@var",
"BTOR",
"BTOR_",
"BTOR_@",
"BTOR_1",
"\"x",
"x\"",
"\"xx\"",
"\"x\"\"x\"",
"x ",
" x",
" x ");
private static final ArrayFormulaType<IntegerFormula, IntegerFormula> ARRAY_TYPE_INT_INT =
FormulaType.getArrayType(IntegerType, IntegerType);
private static final ImmutableList<Solvers> SOLVERS_WITH_PARTIAL_MODEL =
ImmutableList.of(Solvers.Z3, Solvers.PRINCESS);
@Before
public void setup() {
requireModel();
}
@Test
public void testEmpty() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m).isEmpty();
}
assertThat(prover.getModelAssignments()).isEmpty();
}
}
@Test
public void testOnlyTrue() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeTrue());
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m).isEmpty();
}
assertThat(prover.getModelAssignments()).isEmpty();
}
}
@Test
public void testGetSmallIntegers() throws SolverException, InterruptedException {
requireIntegers();
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.makeVariable("x"),
BigInteger.valueOf(10),
"x");
}
@Test
public void testGetNegativeIntegers() throws SolverException, InterruptedException {
requireIntegers();
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(-10)),
imgr.makeVariable("x"),
BigInteger.valueOf(-10),
"x");
}
@Test
public void testGetLargeIntegers() throws SolverException, InterruptedException {
requireIntegers();
BigInteger large = new BigInteger("1000000000000000000000000000000000000000");
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(large)),
imgr.makeVariable("x"),
large,
"x");
}
@Test
public void testGetSmallIntegralRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
testModelGetters(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.makeVariable("x"),
BigInteger.valueOf(1),
"x");
}
@Test
public void testGetLargeIntegralRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
BigInteger large = new BigInteger("1000000000000000000000000000000000000000");
testModelGetters(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(large)),
rmgr.makeVariable("x"),
large,
"x");
}
@Test
public void testGetRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
for (String name : VARIABLE_NAMES) {
testModelGetters(
rmgr.equal(rmgr.makeVariable(name), rmgr.makeNumber(Rational.ofString("1/3"))),
rmgr.makeVariable(name),
Rational.ofString("1/3"),
name);
}
}
/** Test that different names are no problem for Bools in the model. */
@Test
public void testGetBooleans() throws SolverException, InterruptedException {
// Some names are specificly chosen to test the Boolector model
for (String name : VARIABLE_NAMES) {
testModelGetters(bmgr.makeVariable(name), bmgr.makeBoolean(true), true, name);
}
}
/** Test that different names are no problem for Bitvectors in the model. */
@Test
public void testGetBvs() throws SolverException, InterruptedException {
requireBitvectors();
// Some names are specificly chosen to test the Boolector model
// Use 1 instead of 0 or max bv value, as solvers tend to use 0, min or max as default
for (String name : VARIABLE_NAMES) {
testModelGetters(
bvmgr.equal(bvmgr.makeVariable(8, name), bvmgr.makeBitvector(8, 1)),
bvmgr.makeBitvector(8, 1),
BigInteger.ONE,
name);
}
}
/** Test that different names are no problem for Integers in the model. */
@Test
public void testGetInts() throws SolverException, InterruptedException {
requireIntegers();
for (String name : VARIABLE_NAMES) {
testModelGetters(
imgr.equal(imgr.makeVariable(name), imgr.makeNumber(1)),
imgr.makeNumber(1),
BigInteger.ONE,
name);
}
}
/** Test that different names are no problem for Bv UFs in the model. */
@Test
public void testGetBvUfs() throws SolverException, InterruptedException {
requireBitvectors();
// Some names are specificly chosen to test the Boolector model
// Use 1 instead of 0 or max bv value, as solvers tend to use 0, min or max as default
for (String ufName : VARIABLE_NAMES) {
testModelGetters(
bvmgr.equal(
bvmgr.makeBitvector(8, 1),
fmgr.declareAndCallUF(
ufName,
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "var")))),
bvmgr.makeBitvector(8, 1),
BigInteger.ONE,
ufName,
false,
null);
}
}
/** Test that different names are no problem for int UFs in the model. */
@Test
public void testGetIntUfs() throws SolverException, InterruptedException {
requireIntegers();
// Some names are specificly chosen to test the Boolector model
// Use 1 instead of 0 or max bv value, as solvers tend to use 0, min or max as default
for (String ufName : VARIABLE_NAMES) {
testModelGetters(
bmgr.and(
imgr.equal(imgr.makeVariable("var"), imgr.makeNumber(123)),
imgr.equal(
imgr.makeNumber(1),
fmgr.declareAndCallUF(
ufName,
FormulaType.IntegerType,
ImmutableList.of(imgr.makeVariable("var"))))),
imgr.makeNumber(1),
BigInteger.ONE,
ufName,
false,
ImmutableList.of(BigInteger.valueOf(123)));
}
}
@Test
public void testGetUFs() throws SolverException, InterruptedException {
// Boolector does not support integers
if (imgr != null) {
IntegerFormula x =
fmgr.declareAndCallUF("UF", IntegerType, ImmutableList.of(imgr.makeVariable("arg")));
testModelGetters(
bmgr.and(
imgr.equal(x, imgr.makeNumber(1)),
imgr.equal(imgr.makeVariable("arg"), imgr.makeNumber(123))),
x,
BigInteger.ONE,
"UF",
false,
ImmutableList.of(BigInteger.valueOf(123)));
} else {
BitvectorFormula x =
fmgr.declareAndCallUF(
"UF",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "arg")));
testModelGetters(
bmgr.and(
bvmgr.equal(x, bvmgr.makeBitvector(8, 1)),
bvmgr.equal(bvmgr.makeVariable(8, "arg"), bvmgr.makeBitvector(8, 123))),
x,
BigInteger.ONE,
"UF",
false,
ImmutableList.of(BigInteger.valueOf(123)));
}
}
@Test
public void testGetUFsWithMultipleAssignments() throws SolverException, InterruptedException {
requireIntegers();
List<BooleanFormula> constraints = new ArrayList<>();
int num = 4;
for (int i = 0; i < num; i++) {
IntegerFormula arg1 = imgr.makeVariable("arg1" + i);
IntegerFormula arg2 = imgr.makeVariable("arg2" + i);
IntegerFormula arg3 = imgr.makeVariable("arg3" + i);
IntegerFormula func = fmgr.declareAndCallUF("UF", IntegerType, arg1, arg2, arg3);
constraints.add(imgr.equal(func, imgr.makeNumber(2 * i + 31)));
constraints.add(imgr.equal(arg1, imgr.makeNumber(i)));
constraints.add(imgr.equal(arg2, imgr.makeNumber(i + 17)));
constraints.add(imgr.equal(arg3, imgr.makeNumber(i + 23)));
}
BooleanFormula constraint = bmgr.and(constraints);
for (int i = 0; i < num; i++) {
IntegerFormula func =
fmgr.declareAndCallUF(
"UF",
IntegerType,
imgr.makeVariable("arg1" + i),
imgr.makeVariable("arg2" + i),
imgr.makeVariable("arg3" + i));
testModelGetters(
constraint,
func,
BigInteger.valueOf(2 * i + 31),
"UF",
false,
ImmutableList.of(
BigInteger.valueOf(i), BigInteger.valueOf(i + 17), BigInteger.valueOf(i + 23)));
}
}
@Test
public void testGetUFwithMoreParams() throws Exception {
// Boolector does not support integers
if (imgr != null) {
IntegerFormula x =
fmgr.declareAndCallUF(
"UF",
IntegerType,
ImmutableList.of(imgr.makeVariable("arg1"), imgr.makeVariable("arg2")));
testModelGetters(imgr.equal(x, imgr.makeNumber(1)), x, BigInteger.ONE, "UF", false, null);
} else {
BitvectorFormula x =
fmgr.declareAndCallUF(
"UF",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "arg1"), bvmgr.makeVariable(8, "arg2")));
testModelGetters(
bvmgr.equal(x, bvmgr.makeBitvector(8, 1)), x, BigInteger.ONE, "UF", false, null);
}
}
@Test
public void testGetMultipleUFsWithInts() throws Exception {
requireIntegers();
IntegerFormula arg1 = imgr.makeVariable("arg1");
IntegerFormula arg2 = imgr.makeVariable("arg2");
FunctionDeclaration<IntegerFormula> declaration =
fmgr.declareUF("UF", IntegerType, IntegerType);
IntegerFormula app1 = fmgr.callUF(declaration, arg1);
IntegerFormula app2 = fmgr.callUF(declaration, arg2);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula two = imgr.makeNumber(2);
IntegerFormula three = imgr.makeNumber(3);
IntegerFormula four = imgr.makeNumber(4);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
imgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
imgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three),
one,
imgr.equal(fmgr.callUF(declaration, three), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3))),
new ValueAssignment(
fmgr.callUF(declaration, four),
imgr.makeNumber(2),
imgr.equal(fmgr.callUF(declaration, four), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(4))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(imgr.equal(app1, imgr.makeNumber(1)), imgr.equal(app2, imgr.makeNumber(2))));
prover.push(imgr.equal(arg1, imgr.makeNumber(3)));
prover.push(imgr.equal(arg2, imgr.makeNumber(4)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
@Test
public void testGetMultipleUFsWithBvs() throws Exception {
requireBitvectors();
BitvectorFormula arg1 = bvmgr.makeVariable(8, "arg1");
BitvectorFormula arg2 = bvmgr.makeVariable(8, "arg2");
FunctionDeclaration<BitvectorFormula> declaration =
fmgr.declareUF(
"UF", FormulaType.getBitvectorTypeWithSize(8), FormulaType.getBitvectorTypeWithSize(8));
BitvectorFormula app1 = fmgr.callUF(declaration, arg1);
BitvectorFormula app2 = fmgr.callUF(declaration, arg2);
BitvectorFormula one = bvmgr.makeBitvector(8, 1);
BitvectorFormula two = bvmgr.makeBitvector(8, 2);
BitvectorFormula three = bvmgr.makeBitvector(8, 3);
BitvectorFormula four = bvmgr.makeBitvector(8, 4);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
bvmgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
bvmgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three),
one,
bvmgr.equal(fmgr.callUF(declaration, three), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3))),
new ValueAssignment(
fmgr.callUF(declaration, four),
bvmgr.makeBitvector(8, 2),
bvmgr.equal(fmgr.callUF(declaration, four), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(4))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(
bvmgr.equal(app1, bvmgr.makeBitvector(8, 1)),
bvmgr.equal(app2, bvmgr.makeBitvector(8, 2))));
prover.push(bvmgr.equal(arg1, bvmgr.makeBitvector(8, 3)));
prover.push(bvmgr.equal(arg2, bvmgr.makeBitvector(8, 4)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
@Test
public void testGetMultipleUFsWithBvsWithMultipleArguments() throws Exception {
requireBitvectors();
BitvectorFormula arg1 = bvmgr.makeVariable(8, "arg1");
BitvectorFormula arg2 = bvmgr.makeVariable(8, "arg2");
BitvectorFormula arg3 = bvmgr.makeVariable(8, "arg3");
BitvectorFormula arg4 = bvmgr.makeVariable(8, "arg4");
FunctionDeclaration<BitvectorFormula> declaration =
fmgr.declareUF(
"UF",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
BitvectorFormula app1 = fmgr.callUF(declaration, arg1, arg2);
BitvectorFormula app2 = fmgr.callUF(declaration, arg3, arg4);
BitvectorFormula one = bvmgr.makeBitvector(8, 1);
BitvectorFormula two = bvmgr.makeBitvector(8, 2);
BitvectorFormula three = bvmgr.makeBitvector(8, 3);
BitvectorFormula four = bvmgr.makeBitvector(8, 4);
BitvectorFormula five = bvmgr.makeBitvector(8, 5);
BitvectorFormula six = bvmgr.makeBitvector(8, 6);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
bvmgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
bvmgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
arg3,
five,
bvmgr.equal(arg3, five),
"arg3",
BigInteger.valueOf(5),
ImmutableList.of()),
new ValueAssignment(
arg4,
six,
bvmgr.equal(arg4, six),
"arg4",
BigInteger.valueOf(6),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three, four),
one,
bvmgr.equal(fmgr.callUF(declaration, three, four), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3), BigInteger.valueOf(4))),
new ValueAssignment(
fmgr.callUF(declaration, five, six),
bvmgr.makeBitvector(8, 2),
bvmgr.equal(fmgr.callUF(declaration, five, six), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(5), BigInteger.valueOf(6))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(
bvmgr.equal(app1, bvmgr.makeBitvector(8, 1)),
bvmgr.equal(app2, bvmgr.makeBitvector(8, 2))));
prover.push(bvmgr.equal(arg1, bvmgr.makeBitvector(8, 3)));
prover.push(bvmgr.equal(arg2, bvmgr.makeBitvector(8, 4)));
prover.push(bvmgr.equal(arg3, bvmgr.makeBitvector(8, 5)));
prover.push(bvmgr.equal(arg4, bvmgr.makeBitvector(8, 6)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
// var = 1 & Exists boundVar . (boundVar = 0 & var = f(boundVar))
@Test
public void testQuantifiedUF() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
// create query: "(var == 1) && exists bound : (bound == 0 && var == func(bound))"
// then check that the model contains an evaluation "func(0) := 1"
IntegerFormula var = imgr.makeVariable("var");
BooleanFormula varIsOne = imgr.equal(var, imgr.makeNumber(1));
IntegerFormula boundVar = imgr.makeVariable("boundVar");
BooleanFormula boundVarIsZero = imgr.equal(boundVar, imgr.makeNumber(2));
String func = "func";
IntegerFormula funcAtTwo = fmgr.declareAndCallUF(func, IntegerType, imgr.makeNumber(2));
IntegerFormula funcAtBoundVar = fmgr.declareAndCallUF(func, IntegerType, boundVar);
BooleanFormula body = bmgr.and(boundVarIsZero, imgr.equal(var, funcAtBoundVar));
BooleanFormula f = bmgr.and(varIsOne, qmgr.exists(ImmutableList.of(boundVar), body));
IntegerFormula one = imgr.makeNumber(1);
ValueAssignment expectedValueAssignment =
new ValueAssignment(
funcAtTwo,
one,
imgr.equal(funcAtTwo, one),
func,
BigInteger.ONE,
ImmutableList.of(BigInteger.TWO));
// CVC4/5 does not give back bound variable values. Not even in UFs.
if (solverToUse() == Solvers.CVC4 || solverToUse() == Solvers.CVC5) {
expectedValueAssignment =
new ValueAssignment(
funcAtBoundVar,
one,
imgr.equal(funcAtBoundVar, one),
func,
BigInteger.ONE,
ImmutableList.of("boundVar"));
}
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m).contains(expectedValueAssignment);
}
}
}
// var = 1 & boundVar = 1 & Exists boundVar . (boundVar = 0 & var = func(boundVar))
@Test
public void testQuantifiedUF2() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula var = imgr.makeVariable("var");
BooleanFormula varIsOne = imgr.equal(var, imgr.makeNumber(1));
IntegerFormula boundVar = imgr.makeVariable("boundVar");
BooleanFormula boundVarIsZero = imgr.equal(boundVar, imgr.makeNumber(0));
BooleanFormula boundVarIsOne = imgr.equal(boundVar, imgr.makeNumber(1));
String func = "func";
IntegerFormula funcAtZero = fmgr.declareAndCallUF(func, IntegerType, imgr.makeNumber(0));
IntegerFormula funcAtBoundVar = fmgr.declareAndCallUF(func, IntegerType, boundVar);
BooleanFormula body = bmgr.and(boundVarIsZero, imgr.equal(var, funcAtBoundVar));
BooleanFormula f =
bmgr.and(varIsOne, boundVarIsOne, qmgr.exists(ImmutableList.of(boundVar), body));
IntegerFormula one = imgr.makeNumber(1);
ValueAssignment expectedValueAssignment =
new ValueAssignment(
funcAtZero,
one,
imgr.equal(funcAtZero, one),
func,
BigInteger.ONE,
ImmutableList.of(BigInteger.ZERO));
// CVC4/5 does not give back bound variable values. Not even in UFs.
if (solverToUse() == Solvers.CVC4 || solverToUse() == Solvers.CVC5) {
expectedValueAssignment =
new ValueAssignment(
funcAtBoundVar,
one,
imgr.equal(funcAtBoundVar, one),
func,
BigInteger.ONE,
ImmutableList.of("boundVar"));
}
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m).contains(expectedValueAssignment);
}
}
}
@Test
public void testGetBitvectors() throws SolverException, InterruptedException {
requireBitvectors();
if (solver == Solvers.BOOLECTOR) {
// Boolector uses bitvecs length 1 as bools
testModelGetters(
bvmgr.equal(bvmgr.makeVariable(2, "x"), bvmgr.makeBitvector(2, BigInteger.ONE)),
bvmgr.makeVariable(2, "x"),
BigInteger.ONE,
"x");
} else {
testModelGetters(
bvmgr.equal(bvmgr.makeVariable(1, "x"), bvmgr.makeBitvector(1, BigInteger.ONE)),
bvmgr.makeVariable(1, "x"),
BigInteger.ONE,
"x");
}
}
@Test
public void testGetString() throws SolverException, InterruptedException {
requireStrings();
for (String word : new String[] {"", "a", "abc", "1", "123", "-abc", "\"test\"", "\""}) {
testModelGetters(
smgr.equal(smgr.makeVariable("x"), smgr.makeString(word)),
smgr.makeVariable("x"),
word,
"x");
}
}
@Test
public void testGetModelAssignments() throws SolverException, InterruptedException {
if (imgr != null) {
testModelIterator(
bmgr.and(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)),
imgr.equal(imgr.makeVariable("x"), imgr.makeVariable("y"))));
} else {
testModelIterator(
bmgr.and(
bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1)),
bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "y"))));
}
}
@Test
public void testEmptyStackModel() throws SolverException, InterruptedException {
if (imgr != null) {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(imgr.makeNumber(123))).isEqualTo(BigInteger.valueOf(123));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(imgr.makeVariable("y"))).isNull();
} else {
assertThat(m.evaluate(imgr.makeVariable("y"))).isNotNull();
}
}
}
} else {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(bvmgr.makeBitvector(8, 123))).isEqualTo(BigInteger.valueOf(123));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNull();
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNotNull();
}
}
}
}
}
@Test
public void testNonExistantSymbol() throws SolverException, InterruptedException {
if (imgr != null) {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeBoolean(true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(imgr.makeVariable("y"))).isNull();
} else {
assertThat(m.evaluate(imgr.makeVariable("y"))).isNotNull();
}
}
}
} else {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeBoolean(true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNull();
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNotNull();
}
}
}
}
}
@Test
public void testPartialModels() throws SolverException, InterruptedException {
assume()
.withMessage("As of now, only Z3 and Princess support partial models")
.that(solver)
.isIn(SOLVERS_WITH_PARTIAL_MODEL);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
prover.push(imgr.equal(x, x));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(x)).isEqualTo(null);
assertThat(m).isEmpty();
}
}
}
@Test
public void testPartialModels2() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
if (imgr != null) {
IntegerFormula x = imgr.makeVariable("x");
prover.push(imgr.greaterThan(x, imgr.makeNumber(0)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
// it works now, but maybe the model "x=1" for the constraint "x>0" is not valid for new
// solvers.
}
} else {
BitvectorFormula x = bvmgr.makeVariable(8, "x");
prover.push(bvmgr.greaterThan(x, bvmgr.makeBitvector(8, 0), true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (solver != Solvers.BOOLECTOR) {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
} else {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.valueOf(64));
}
// it works now, but maybe the model "x=1" for the constraint "x>0" is not valid for new
// solvers.
// Can confirm ;D Boolector likes to take the "max" values for bitvectors instead of the
// min; as a result it returns 64
}
}
}
}
@Test
public void testPartialModelsUF() throws SolverException, InterruptedException {
assume()
.withMessage("As of now, only Z3 supports partial model evaluation")
.that(solver)
.isIn(ImmutableList.of(Solvers.Z3));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula f = fmgr.declareAndCallUF("f", IntegerType, x);
prover.push(imgr.equal(x, imgr.makeNumber(1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(f)).isEqualTo(null);
}
}
}
@Test
public void testEvaluatingConstants() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeVariable("b"));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
if (imgr != null) {
assertThat(m.evaluate(imgr.makeNumber(0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(imgr.makeNumber(1))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(imgr.makeNumber(100))).isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
}
if (bvmgr != null) {
if (solver == Solvers.BOOLECTOR) {
for (int i : new int[] {2, 4, 8, 32, 64, 1000}) {
assertThat(m.evaluate(bvmgr.makeBitvector(i, 0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.makeBitvector(i, 1))).isEqualTo(BigInteger.ONE);
}
} else {
for (int i : new int[] {1, 2, 4, 8, 32, 64, 1000}) {
assertThat(m.evaluate(bvmgr.makeBitvector(i, 0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.makeBitvector(i, 1))).isEqualTo(BigInteger.ONE);
}
}
}
}
}
}
@Test
public void testEvaluatingConstantsWithOperation() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeVariable("b"));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
if (imgr != null) {
assertThat(m.evaluate(imgr.add(imgr.makeNumber(45), imgr.makeNumber(55))))
.isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(imgr.subtract(imgr.makeNumber(123), imgr.makeNumber(23))))
.isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(bmgr.and(bmgr.makeBoolean(true), bmgr.makeBoolean(true)))).isTrue();
}
if (bvmgr != null) {
if (solver == Solvers.BOOLECTOR) {
for (int i : new int[] {2, 4, 8, 32, 64, 1000}) {
BitvectorFormula zero = bvmgr.makeBitvector(i, 0);
BitvectorFormula one = bvmgr.makeBitvector(i, 1);
assertThat(m.evaluate(bvmgr.add(zero, zero))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.add(zero, one))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(bvmgr.subtract(one, one))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.subtract(one, zero))).isEqualTo(BigInteger.ONE);
}
} else {
for (int i : new int[] {1, 2, 4, 8, 32, 64, 1000}) {
BitvectorFormula zero = bvmgr.makeBitvector(i, 0);
BitvectorFormula one = bvmgr.makeBitvector(i, 1);
assertThat(m.evaluate(bvmgr.add(zero, zero))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.add(zero, one))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(bvmgr.subtract(one, one))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.subtract(one, zero))).isEqualTo(BigInteger.ONE);
}
}
}
}
}
}
@Test
public void testNonVariableValues() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment that works beyond the section where you put it!
IntegerFormula select1Store7in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
BooleanFormula selectStoreEq1 = imgr.equal(select1Store7in1, imgr.makeNumber(1));
IntegerFormula select1Store7in1store7in2 =
amgr.select(
amgr.store(
amgr.store(array1, imgr.makeNumber(2), imgr.makeNumber(7)),
imgr.makeNumber(1),
imgr.makeNumber(7)),
imgr.makeNumber(1));
IntegerFormula select1Store1in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(1)), imgr.makeNumber(1));
IntegerFormula arithIs7 =
imgr.add(imgr.add(imgr.makeNumber(5), select1Store1in1), select1Store1in1);
// (arr[1] = 7)[1] = 1 -> ...
// false -> doesn't matter
BooleanFormula assert1 = bmgr.implication(selectStoreEq1, selectEq0);
// (arr[1] = 7)[1] != 1 -> ((arr[2] = 7)[1] = 7)[1] = 7 is true
BooleanFormula assert2 =
bmgr.implication(bmgr.not(selectStoreEq1), imgr.equal(select1Store7in1store7in2, arithIs7));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// make the right part of the impl in assert1 fail such that the left is negated
prover.push(bmgr.not(selectEq0));
prover.push(assert1);
prover.push(assert2);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(select1Store7in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(select1Store7in1store7in2)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(arithIs7)).isEqualTo(BigInteger.valueOf(7));
}
}
}
@Test
public void testNonVariableValues2() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment that works beyond the section where you put it!
IntegerFormula select1Store7in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
BooleanFormula selectStoreEq1 = imgr.equal(select1Store7in1, imgr.makeNumber(1));
IntegerFormula select1Store7in1store3in1 =
amgr.select(
amgr.store(
amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(3)),
imgr.makeNumber(1),
imgr.makeNumber(7)),
imgr.makeNumber(1));
IntegerFormula select1Store1in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(1)), imgr.makeNumber(1));
IntegerFormula arithIs7 =
imgr.add(imgr.add(imgr.makeNumber(5), select1Store1in1), select1Store1in1);
// (arr[1] = 7)[1] = 1 -> ...
// false -> doesn't matter
BooleanFormula assert1 = bmgr.implication(selectStoreEq1, selectEq0);
// (arr[1] = 7)[1] != 1 -> ((arr[1] = 3)[1] = 7)[1] = 7 is true
BooleanFormula assert2 =
bmgr.implication(bmgr.not(selectStoreEq1), imgr.equal(select1Store7in1store3in1, arithIs7));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// make the right part of the impl in assert1 fail such that the left is negated
prover.push(bmgr.not(selectEq0));
prover.push(assert1);
prover.push(assert2);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(select1Store7in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(select1Store7in1store3in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(arithIs7)).isEqualTo(BigInteger.valueOf(7));
}
}
}
@Test
public void testGetIntArrays() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array =
amgr.makeArray("array", IntegerType, IntegerType);
ArrayFormula<IntegerFormula, IntegerFormula> updated =
amgr.store(array, imgr.makeNumber(1), imgr.makeNumber(1));
IntegerFormula selected = amgr.select(updated, imgr.makeNumber(1));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(imgr.equal(selected, imgr.makeNumber(1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selected)).isEqualTo(BigInteger.ONE);
// check that model evaluation applies formula simplification or constant propagation.
ArrayFormula<IntegerFormula, IntegerFormula> stored = array;
for (int i = 0; i < 10; i++) {
stored = amgr.store(stored, imgr.makeNumber(i), imgr.makeNumber(i));
// zero is the inner element of array
assertThat(m.evaluate(amgr.select(stored, imgr.makeNumber(0))))
.isEqualTo(BigInteger.ZERO);
// i is the outer element of array
assertThat(m.evaluate(amgr.select(stored, imgr.makeNumber(i))))
.isEqualTo(BigInteger.valueOf(i));
}
}
}
}
@Test
public void testGetArrays2() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireBitvectors();
ArrayFormula<BitvectorFormula, BitvectorFormula> array =
amgr.makeArray(
"array",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
ArrayFormula<BitvectorFormula, BitvectorFormula> updated =
amgr.store(array, bvmgr.makeBitvector(8, 1), bvmgr.makeBitvector(8, 1));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bvmgr.equal(amgr.select(updated, bvmgr.makeBitvector(8, 1)), bvmgr.makeBitvector(8, 1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(amgr.select(updated, bvmgr.makeBitvector(8, 1))))
.isEqualTo(BigInteger.ONE);
}
}
}
@Test
public void testGetArrays6() throws SolverException, InterruptedException {
requireArrays();
requireParser();
BooleanFormula f =
mgr.parse(
"(declare-fun |pi@2| () Int)\n"
+ "(declare-fun *unsigned_int@1 () (Array Int Int))\n"
+ "(declare-fun |z2@2| () Int)\n"
+ "(declare-fun |z1@2| () Int)\n"
+ "(declare-fun |t@2| () Int)\n"
+ "(declare-fun |__ADDRESS_OF_t| () Int)\n"
+ "(declare-fun *char@1 () (Array Int Int))\n"
+ "(assert"
+ " (and (= |t@2| 50)"
+ " (not (<= |__ADDRESS_OF_t| 0))"
+ " (= |z1@2| |__ADDRESS_OF_t|)"
+ " (= (select *char@1 |__ADDRESS_OF_t|) |t@2|)"
+ " (= |z2@2| |z1@2|)"
+ " (= |pi@2| |z2@2|)"
+ " (not (= (select *unsigned_int@1 |pi@2|) 50))))");
testModelIterator(f);
}
@Test
public void testGetArrays3() throws SolverException, InterruptedException {
requireParser();
requireArrays();
assume()
.withMessage("As of now, only Princess does not support multi-dimensional arrays")
.that(solver)
.isNotSameInstanceAs(Solvers.PRINCESS);
// create formula for "arr[5][3][1]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int (Array Int (Array Int Int))))\n"
+ "(assert (and"
+ " (= (select (select (select arr 5) 3) 1) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
ArrayFormulaType<
IntegerFormula,
ArrayFormula<IntegerFormula, ArrayFormula<IntegerFormula, IntegerFormula>>>
arrType =
FormulaType.getArrayType(
IntegerType, FormulaType.getArrayType(IntegerType, ARRAY_TYPE_INT_INT));
testModelGetters(
f,
amgr.select(
amgr.select(
amgr.select(amgr.makeArray("arr", arrType), imgr.makeNumber(5)),
imgr.makeNumber(3)),
imgr.makeNumber(1)),
BigInteger.valueOf(123),
"arr",
true,
ImmutableList.of(BigInteger.valueOf(5), BigInteger.valueOf(3), BigInteger.ONE));
}
@Test
public void testGetArrays4() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arr 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arr", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arr",
true,
ImmutableList.of(BigInteger.valueOf(5)));
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public void testGetArrays4invalid() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arr 5) x)"
+ " (= x 123)"
+ "))");
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
m.evaluate(amgr.makeArray("arr", ARRAY_TYPE_INT_INT));
}
}
}
@Test
public void testGetArrays5() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arr 6 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arr", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arr",
true,
ImmutableList.of(BigInteger.valueOf(5)));
}
@Test
public void testGetArrays5b() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && arr[6]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arrgh 5) x)"
+ " (= (select arrgh 6) x)"
+ " (= x 123)"
+ " (= (select (store ahoi 66 x) 55) x)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(5)));
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(6)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(6)));
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(55)),
BigInteger.valueOf(123),
"ahoi",
true,
ImmutableList.of(BigInteger.valueOf(55)));
// The value for 'ahoi[66]' is not determined by the constraints from above,
// because we only 'store' it in (a copy of) the array, but never read it.
// Thus, the following test case depends on the solver and would be potentially wrong:
//
// testModelGetters(
// f,
// amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(66)),
// BigInteger.valueOf(123),
// "ahoi",
// true);
}
@Test
public void testGetArrays5c() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(5)));
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true,
ImmutableList.of(BigInteger.valueOf(5)));
}
@Test
public void testGetArrays5d() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 x) 7) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(5)));
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(7)),
BigInteger.valueOf(123),
"ahoi",
true,
ImmutableList.of(BigInteger.valueOf(7)));
}
@Test
public void testGetArrays5e() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arrgh[5:6]==[x,x] && ahoi[5,7] == [x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 7 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(5)));
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true,
ImmutableList.of(BigInteger.valueOf(5)));
}
@Test
public void testGetArrays5f() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arrgh[5:6]==[x,x] && ahoi[5,6] == [x,y] && y = 125 && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun y () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 y) 5) x)"
+ " (= x 123)"
+ " (= y 125)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true,
ImmutableList.of(BigInteger.valueOf(5)));
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true,
ImmutableList.of(BigInteger.valueOf(5)));
}
@Test
public void testGetArrays7() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment! This is just so that the implication fails and arr[1] =
// 0
BooleanFormula selectStore =
imgr.equal(
amgr.select(
amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1)),
imgr.makeNumber(0));
BooleanFormula assert1 = bmgr.implication(bmgr.not(selectEq0), selectStore);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(assert1);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selected)).isEqualTo(BigInteger.ZERO);
}
}
}
@Test
public void testGetArrays8() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
IntegerFormula selectStore =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
// Note that store is not an assignment! This is just used to make the implication fail and
// arr[1] =
// 0
BooleanFormula selectStoreEq0 = imgr.equal(selectStore, imgr.makeNumber(0));
IntegerFormula arithEq7 =
imgr.subtract(
imgr.multiply(imgr.add(imgr.makeNumber(1), imgr.makeNumber(2)), imgr.makeNumber(3)),
imgr.makeNumber(2));
BooleanFormula selectStoreEq7 = imgr.equal(selectStore, arithEq7);
// arr[1] = 0 -> (arr[1] = 7)[1] = 0
// if the left is true, the right has to be, but its false => left false => overall TRUE
BooleanFormula assert1 = bmgr.implication(selectEq0, selectStoreEq0);
// arr[1] != 0 -> (arr[1] = 7)[1] = 7
// left has to be true because of assert1 -> right has to be true as well
BooleanFormula assert2 = bmgr.implication(bmgr.not(selectEq0), selectStoreEq7);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(assert1, assert2));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selectStore)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(arithEq7)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
}
}
}
@Test
public void testGetArrays9() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array1", IntegerType, IntegerType);
ArrayFormula<IntegerFormula, IntegerFormula> array2 =
amgr.makeArray("array2", IntegerType, IntegerType);
IntegerFormula selected1 = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected1, imgr.makeNumber(0));
BooleanFormula selectGT0 = imgr.greaterThan(selected1, imgr.makeNumber(0));
BooleanFormula selectGTEmin1 = imgr.greaterOrEquals(selected1, imgr.makeNumber(-1));
IntegerFormula selected2 = amgr.select(array2, imgr.makeNumber(1));
BooleanFormula arr2LT0 = imgr.lessOrEquals(selected2, imgr.makeNumber(0));
BooleanFormula select2GTEmin1 = imgr.greaterOrEquals(selected2, imgr.makeNumber(-1));
// arr1[1] > 0 -> arr1[1] = 0
// obviously false => arr[1] <= 0
BooleanFormula assert1 = bmgr.implication(selectGT0, selectEq0);
// arr1[1] > 0 -> arr2[1] <= 1
// left holds because of the first assertion => arr2[1] <= 0
BooleanFormula assert2 = bmgr.implication(bmgr.not(selectGT0), arr2LT0);
// if now arr2[1] >= -1 -> arr1[1] >= -1
// holds
BooleanFormula assert3 = bmgr.implication(select2GTEmin1, selectGTEmin1);
BooleanFormula assert4 = imgr.greaterThan(selected2, imgr.makeNumber(-2));
// basicly just says that: -1 <= arr[1] <= 0 & -1 <= arr2[1] <= 0 up to this point
// make the 2 array[1] values unequal
BooleanFormula assert5 = bmgr.not(imgr.equal(selected1, selected2));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(assert1, assert2, assert3, assert4, assert5));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
if (m.evaluate(selected1).equals(BigInteger.valueOf(-1))) {
assertThat(m.evaluate(selected1)).isEqualTo(BigInteger.valueOf(-1));
assertThat(m.evaluate(selected2)).isEqualTo(BigInteger.valueOf(0));
} else {
assertThat(m.evaluate(selected1)).isEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(selected2)).isEqualTo(BigInteger.valueOf(-1));
}
}
}
}
private void testModelIterator(BooleanFormula f) throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(m).inOrder();
}
}
}
private void testModelGetters(
BooleanFormula constraint, Formula variable, Object expectedValue, String varName)
throws SolverException, InterruptedException {
testModelGetters(constraint, variable, expectedValue, varName, false);
}
private void testModelGetters(
BooleanFormula constraint,
Formula variable,
Object expectedValue,
String varName,
boolean isArray)
throws SolverException, InterruptedException {
testModelGetters(constraint, variable, expectedValue, varName, isArray, ImmutableList.of());
}
/**
* @param ufArgs use NULL to disable the argument check. Use NULL with care, whenever a
* nondeterministic result is expected, e.g., different assignments from different solvers!
*/
private void testModelGetters(
BooleanFormula constraint,
Formula variable,
Object expectedValue,
String varName,
boolean isArray,
@Nullable List<Object> ufArgs)
throws SolverException, InterruptedException {
List<BooleanFormula> modelAssignments = new ArrayList<>();
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(constraint);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(variable)).isEqualTo(expectedValue);
for (ValueAssignment va : m) {
modelAssignments.add(va.getAssignmentAsFormula());
}
List<ValueAssignment> relevantAssignments =
prover.getModelAssignments().stream()
.filter(
assignment ->
assignment.getName().equals(varName)
&& (ufArgs == null
|| assignment.getArgumentsInterpretation().equals(ufArgs)))
.collect(Collectors.toList());
assert_()
.withMessage(
"No relevant assignment in model %s available for name '%s' with %s found.",
prover.getModelAssignments(),
varName,
ufArgs == null ? "arbitrary parameters" : ("parameters " + ufArgs))
.that(relevantAssignments)
.isNotEmpty();
if (isArray) {
List<ValueAssignment> arrayAssignments =
relevantAssignments.stream()
.filter(assignment -> expectedValue.equals(assignment.getValue()))
.collect(Collectors.toList());
assertThat(arrayAssignments)
.isNotEmpty(); // at least one assignment should have the wanted value
} else {
// normal variables have exactly one evaluation assigned to their name
assertThat(relevantAssignments).hasSize(1);
ValueAssignment assignment = Iterables.getOnlyElement(relevantAssignments);
assertThat(assignment.getValue()).isEqualTo(expectedValue);
assertThat(m.evaluate(assignment.getKey())).isEqualTo(expectedValue);
}
// before closing the model
checkModelAssignmentsValid(constraint, modelAssignments);
}
// after closing the model, before closing the prover
checkModelAssignmentsValid(constraint, modelAssignments);
}
// after closing the prover.
checkModelAssignmentsValid(constraint, modelAssignments);
}
/**
* This method checks two things: First, we check whether the model evaluation is implied by the
* given constraint, i.e., whether this is a valid model. Second, we check whether all formulas
* are still valid before/after closing the model and before/after closing the corresponding
* prover.
*/
private void checkModelAssignmentsValid(
BooleanFormula constraint, List<BooleanFormula> pModelAssignments)
throws SolverException, InterruptedException {
// This can't work in Boolector with ufs as it always crashes with:
// [btorslvfun] add_function_inequality_constraints: equality over non-array lambdas not
// supported yet
// TODO: only filter out UF formulas here, not all
if (solver != Solvers.BOOLECTOR) {
// CVC5 crashes here
assertThatFormula(bmgr.and(pModelAssignments)).implies(constraint);
}
}
@Test
public void ufTest() throws SolverException, InterruptedException {
requireQuantifiers();
requireBitvectors();
// only Z3 fulfills these requirements
assume()
.withMessage("solver does not implement optimisation")
.that(solverToUse())
.isEqualTo(Solvers.Z3);
BitvectorType t32 = FormulaType.getBitvectorTypeWithSize(32);
FunctionDeclaration<BitvectorFormula> si1 = fmgr.declareUF("*signed_int@1", t32, t32);
FunctionDeclaration<BitvectorFormula> si2 = fmgr.declareUF("*signed_int@2", t32, t32);
BitvectorFormula ctr = bvmgr.makeVariable(t32, "*signed_int@1@counter");
BitvectorFormula adr = bvmgr.makeVariable(t32, "__ADDRESS_OF_test");
BitvectorFormula num0 = bvmgr.makeBitvector(32, 0);
BitvectorFormula num4 = bvmgr.makeBitvector(32, 4);
BitvectorFormula num10 = bvmgr.makeBitvector(32, 10);
BooleanFormula a11 =
bmgr.implication(
bmgr.and(
bvmgr.lessOrEquals(adr, ctr, false),
bvmgr.lessThan(ctr, bvmgr.add(adr, num10), false)),
bvmgr.equal(fmgr.callUF(si2, ctr), num0));
BooleanFormula a21 =
bmgr.not(
bmgr.and(
bvmgr.lessOrEquals(adr, ctr, false),
bvmgr.lessThan(ctr, bvmgr.add(adr, num10), false)));
BooleanFormula body =
bmgr.and(
a11, bmgr.implication(a21, bvmgr.equal(fmgr.callUF(si2, ctr), fmgr.callUF(si1, ctr))));
BooleanFormula a1 = qmgr.forall(ctr, body);
BooleanFormula a2 =
bvmgr.equal(fmgr.callUF(si1, bvmgr.add(adr, bvmgr.multiply(num4, num0))), num0);
BooleanFormula f = bmgr.and(a1, bvmgr.lessThan(num0, adr, true), bmgr.not(a2));
checkModelIteration(f, true);
checkModelIteration(f, false);
}
@SuppressWarnings("resource")
private void checkModelIteration(BooleanFormula f, boolean useOptProver)
throws SolverException, InterruptedException {
ImmutableList<ValueAssignment> assignments;
try (BasicProverEnvironment<?> prover =
useOptProver
? context.newOptimizationProverEnvironment(ProverOptions.GENERATE_MODELS)
: context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(m).inOrder();
assignments = prover.getModelAssignments();
}
}
assertThat(assignments.size())
.isEqualTo(assignments.stream().map(ValueAssignment::getKey).distinct().count());
List<BooleanFormula> assignmentFormulas = new ArrayList<>();
for (ValueAssignment va : assignments) {
assignmentFormulas.add(va.getAssignmentAsFormula());
assertThatFormula(va.getAssignmentAsFormula())
.isEqualTo(makeAssignment(va.getKey(), va.getValueAsFormula()));
assertThat(va.getValue().getClass())
.isIn(ImmutableList.of(Boolean.class, BigInteger.class, Rational.class, Double.class));
}
// Check that model is not contradicting
assertThatFormula(bmgr.and(assignmentFormulas)).isSatisfiable();
// Check that model does not contradict formula.
// Check for implication is not possible, because formula "x=y" does not imply "{x=0,y=0}" and
// formula "A = (store EMPTY x y)" is not implied by "{x=0,y=0,(select A 0)=0}" (EMPTY != A).
assertThatFormula(bmgr.and(f, bmgr.and(assignmentFormulas))).isSatisfiable();
}
/**
* Short-cut in cases where the type of the formula is unknown. Delegates to the corresponding
* [boolean, integer, bitvector, ...] formula manager.
*/
@SuppressWarnings("unchecked")
private BooleanFormula makeAssignment(Formula pFormula1, Formula pFormula2) {
FormulaType<?> pType = mgr.getFormulaType(pFormula1);
assertWithMessage(
"Trying to equalize two formulas %s and %s of different types %s and %s",
pFormula1, pFormula2, pType, mgr.getFormulaType(pFormula2))
.that(mgr.getFormulaType(pFormula1).equals(mgr.getFormulaType(pFormula2)))
.isTrue();
if (pType.isBooleanType()) {
return bmgr.equivalence((BooleanFormula) pFormula1, (BooleanFormula) pFormula2);
} else if (pType.isIntegerType()) {
return imgr.equal((IntegerFormula) pFormula1, (IntegerFormula) pFormula2);
} else if (pType.isRationalType()) {
return rmgr.equal((RationalFormula) pFormula1, (RationalFormula) pFormula2);
} else if (pType.isBitvectorType()) {
return bvmgr.equal((BitvectorFormula) pFormula1, (BitvectorFormula) pFormula2);
} else if (pType.isFloatingPointType()) {
return fpmgr.assignment((FloatingPointFormula) pFormula1, (FloatingPointFormula) pFormula2);
} else if (pType.isArrayType()) {
@SuppressWarnings("rawtypes")
ArrayFormula f2 = (ArrayFormula) pFormula2;
return amgr.equivalence((ArrayFormula<?, ?>) pFormula1, f2);
}
throw new IllegalArgumentException(
"Cannot make equality of formulas with type " + pType + " in the Solver!");
}
@Test
public void quantifierTestShort() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula ctr = imgr.makeVariable("x");
BooleanFormula body = imgr.equal(ctr, imgr.makeNumber(0));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// exists x : x==0
prover.push(qmgr.exists(ctr, body));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
for (ValueAssignment v : m) {
// a value-assignment might have a different name, but the value should be "0".
assertThat(BigInteger.ZERO.equals(v.getValue())).isTrue();
}
}
prover.pop();
// x==0
prover.push(body);
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
ValueAssignment v = m.iterator().next();
assertThat("x".equals(v.getName())).isTrue();
assertThat(BigInteger.ZERO.equals(v.getValue())).isTrue();
}
}
}
private static final String SMALL_ARRAY_QUERY =
"(declare-fun A1 () (Array Int Int))"
+ "(declare-fun A2 () (Array Int Int))"
+ "(declare-fun X () Int)"
+ "(declare-fun Y () Int)"
+ "(assert (= A1 (store A2 X Y)))";
private static final String BIG_ARRAY_QUERY =
"(declare-fun |V#2@| () Int)"
+ "(declare-fun z3name!115 () Int)"
+ "(declare-fun P42 () Bool)"
+ "(declare-fun M@3 () Int)"
+ "(declare-fun P43 () Bool)"
+ "(declare-fun |V#1@| () Int)"
+ "(declare-fun z3name!114 () Int)"
+ "(declare-fun P44 () Bool)"
+ "(declare-fun M@2 () Int)"
+ "(declare-fun P45 () Bool)"
+ "(declare-fun |It15@5| () Int)"
+ "(declare-fun |It13@5| () Int)"
+ "(declare-fun |H@12| () (Array Int Int))"
+ "(declare-fun |H@13| () (Array Int Int))"
+ "(declare-fun |It14@5| () Int)"
+ "(declare-fun |IN@5| () Int)"
+ "(declare-fun |It12@5| () Int)"
+ "(declare-fun |It11@5| () Int)"
+ "(declare-fun |It9@5| () Int)"
+ "(declare-fun |H@11| () (Array Int Int))"
+ "(declare-fun |It10@5| () Int)"
+ "(declare-fun |It8@5| () Int)"
+ "(declare-fun |Anew@3| () Int)"
+ "(declare-fun |Aprev@3| () Int)"
+ "(declare-fun |H@10| () (Array Int Int))"
+ "(declare-fun |At7@5| () Int)"
+ "(declare-fun |H@9| () (Array Int Int))"
+ "(declare-fun |At6@5| () Int)"
+ "(declare-fun |Anext@3| () Int)"
+ "(declare-fun |H@8| () (Array Int Int))"
+ "(declare-fun |At5@5| () Int)"
+ "(declare-fun |H@7| () (Array Int Int))"
+ "(declare-fun |At4@5| () Int)"
+ "(declare-fun |at3@5| () Int)"
+ "(declare-fun |ahead@3| () Int)"
+ "(declare-fun |anew@3| () Int)"
+ "(declare-fun gl@ () Int)"
+ "(declare-fun |It7@5| () Int)"
+ "(declare-fun |It6@5| () Int)"
+ "(declare-fun |It5@5| () Int)"
+ "(declare-fun |Ivalue@3| () Int)"
+ "(declare-fun i@2 () (Array Int Int))"
+ "(declare-fun i@3 () (Array Int Int))"
+ "(declare-fun P46 () Bool)"
+ "(declare-fun |It4@5| () Int)"
+ "(declare-fun |It4@3| () Int)"
+ "(declare-fun |IT@5| () Int)"
+ "(declare-fun |gl_read::T@4| () Int)"
+ "(declare-fun __VERIFIER_nondet_int@4 () Int)"
+ "(declare-fun |It15@3| () Int)"
+ "(declare-fun |It13@3| () Int)"
+ "(declare-fun |H@6| () (Array Int Int))"
+ "(declare-fun |It14@3| () Int)"
+ "(declare-fun |IN@3| () Int)"
+ "(declare-fun |It12@3| () Int)"
+ "(declare-fun |It11@3| () Int)"
+ "(declare-fun |It9@3| () Int)"
+ "(declare-fun |H@5| () (Array Int Int))"
+ "(declare-fun |It10@3| () Int)"
+ "(declare-fun |It8@3| () Int)"
+ "(declare-fun |Anew@2| () Int)"
+ "(declare-fun |Aprev@2| () Int)"
+ "(declare-fun |H@4| () (Array Int Int))"
+ "(declare-fun |At7@3| () Int)"
+ "(declare-fun |H@3| () (Array Int Int))"
+ "(declare-fun |At6@3| () Int)"
+ "(declare-fun |Anext@2| () Int)"
+ "(declare-fun |H@2| () (Array Int Int))"
+ "(declare-fun |At5@3| () Int)"
+ "(declare-fun |H@1| () (Array Int Int))"
+ "(declare-fun |At4@3| () Int)"
+ "(declare-fun |at3@3| () Int)"
+ "(declare-fun |ahead@2| () Int)"
+ "(declare-fun |anew@2| () Int)"
+ "(declare-fun |It7@3| () Int)"
+ "(declare-fun |It6@3| () Int)"
+ "(declare-fun |It5@3| () Int)"
+ "(declare-fun |Ivalue@2| () Int)"
+ "(declare-fun i@1 () (Array Int Int))"
+ "(declare-fun P47 () Bool)"
+ "(declare-fun |IT@3| () Int)"
+ "(declare-fun |gl_read::T@3| () Int)"
+ "(declare-fun __VERIFIER_nondet_int@2 () Int)"
+ "(assert "
+ " (and (not (<= gl@ 0))"
+ " (not (<= gl@ (- 64)))"
+ " (= |gl_read::T@3| __VERIFIER_nondet_int@2)"
+ " (= |Ivalue@2| |gl_read::T@3|)"
+ " (= |It4@3| 20)"
+ " (= |IT@3| z3name!114)"
+ " (not (<= |V#1@| 0))"
+ " (= |IN@3| |IT@3|)"
+ " (not (<= |V#1@| (+ 64 gl@)))"
+ " (not (<= |V#1@| (- 160)))"
+ " (not (<= (+ |V#1@| (* 8 |It4@3|)) 0))"
+ " (or (and P47 (not (<= |IN@3| 0))) (and (not P47) (not (>= |IN@3| 0))))"
+ " (= i@2 (store i@1 |IN@3| |Ivalue@2|))"
+ " (= |It5@3| |IN@3|)"
+ " (= |It6@3| (+ 4 |It5@3|))"
+ " (= |It7@3| |It6@3|)"
+ " (= |anew@2| |It7@3|)"
+ " (= |ahead@2| gl@)"
+ " (= |at3@3| (select |H@1| |ahead@2|))"
+ " (= |Anew@2| |anew@2|)"
+ " (= |Aprev@2| |ahead@2|)"
+ " (= |Anext@2| |at3@3|)"
+ " (= |At4@3| |Anext@2|)"
+ " (= |At5@3| (+ 4 |At4@3|))"
+ " (= |H@2| (store |H@1| |At5@3| |Anew@2|))"
+ " (= |H@3| (store |H@2| |Anew@2| |Anext@2|))"
+ " (= |At6@3| |Anew@2|)"
+ " (= |At7@3| (+ 4 |At6@3|))"
+ " (= |H@4| (store |H@3| |At7@3| |Aprev@2|))"
+ " (= |H@5| (store |H@4| |Aprev@2| |Anew@2|))"
+ " (= |It8@3| |IN@3|)"
+ " (= |It9@3| (+ 12 |It8@3|))"
+ " (= |It10@3| |IN@3|)"
+ " (= |It11@3| (+ 12 |It10@3|))"
+ " (= |H@6| (store |H@5| |It9@3| |It11@3|))"
+ " (= |It12@3| |IN@3|)"
+ " (= |It13@3| (+ 12 |It12@3|))"
+ " (= |It14@3| |IN@3|)"
+ " (= |It15@3| (+ 12 |It14@3|))"
+ " (= |H@7| (store |H@6| |It13@3| |It15@3|))"
+ " (= |gl_read::T@4| __VERIFIER_nondet_int@4)"
+ " (= |Ivalue@3| |gl_read::T@4|)"
+ " (= |It4@5| 20)"
+ " (= |IT@5| z3name!115)"
+ " (not (<= |V#2@| 0))"
+ " (= |IN@5| |IT@5|)"
+ " (not (<= |V#2@| (+ |V#1@| (* 8 |It4@3|))))"
+ " (not (<= |V#2@| (+ 160 |V#1@|)))"
+ " (not (<= |V#2@| (- 160)))"
+ " (not (<= (+ |V#2@| (* 8 |It4@5|)) 0))"
+ " (or (and P46 (not (<= |IN@5| 0))) (and (not P46) (not (>= |IN@5| 0))))"
+ " (= i@3 (store i@2 |IN@5| |Ivalue@3|))"
+ " (= |It5@5| |IN@5|)"
+ " (= |It6@5| (+ 4 |It5@5|))"
+ " (= |It7@5| |It6@5|)"
+ " (= |anew@3| |It7@5|)"
+ " (= |ahead@3| gl@)"
+ " (= |at3@5| (select |H@7| |ahead@3|))"
+ " (= |Anew@3| |anew@3|)"
+ " (= |Aprev@3| |ahead@3|)"
+ " (= |Anext@3| |at3@5|)"
+ " (= |At4@5| |Anext@3|)"
+ " (= |At5@5| (+ 4 |At4@5|))"
+ " (= |H@8| (store |H@7| |At5@5| |Anew@3|))"
+ " (= |H@9| (store |H@8| |Anew@3| |Anext@3|))"
+ " (= |At6@5| |Anew@3|)"
+ " (= |At7@5| (+ 4 |At6@5|))"
+ " (= |H@10| (store |H@9| |At7@5| |Aprev@3|))"
+ " (= |H@11| (store |H@10| |Aprev@3| |Anew@3|))"
+ " (= |It8@5| |IN@5|)"
+ " (= |It9@5| (+ 12 |It8@5|))"
+ " (= |It10@5| |IN@5|)"
+ " (= |It11@5| (+ 12 |It10@5|))"
+ " (= |H@12| (store |H@11| |It9@5| |It11@5|))"
+ " (= |It12@5| |IN@5|)"
+ " (= |It13@5| (+ 12 |It12@5|))"
+ " (= |It14@5| |IN@5|)"
+ " (= |It15@5| (+ 12 |It14@5|))"
+ " (= |H@13| (store |H@12| |It13@5| |It15@5|))"
+ " (or (and P45 (not (= M@2 0))) (and (not P45) (= z3name!114 0)))"
+ " (or (and P44 (= M@2 0)) (and (not P44) (= z3name!114 |V#1@|)))"
+ " (or (and P43 (not (= M@3 0))) (and (not P43) (= z3name!115 0)))"
+ " (or (and P42 (= M@3 0)) (and (not P42) (= z3name!115 |V#2@|)))))";
private static final String MEDIUM_ARRAY_QUERY =
"(declare-fun |H@1| () (Array Int Int))"
+ "(declare-fun |H@2| () (Array Int Int))"
+ "(declare-fun |H@3| () (Array Int Int))"
+ "(declare-fun |H@4| () (Array Int Int))"
+ "(declare-fun |H@5| () (Array Int Int))"
+ "(declare-fun |H@6| () (Array Int Int))"
+ "(declare-fun |H@7| () (Array Int Int))"
+ "(declare-fun |H@8| () (Array Int Int))"
+ "(declare-fun |H@9| () (Array Int Int))"
+ "(declare-fun |H@10| () (Array Int Int))"
+ "(declare-fun |H@11| () (Array Int Int))"
+ "(declare-fun |H@12| () (Array Int Int))"
+ "(declare-fun |H@13| () (Array Int Int))"
+ "(declare-fun I10 () Int)"
+ "(declare-fun I11 () Int)"
+ "(declare-fun I12 () Int)"
+ "(declare-fun I13 () Int)"
+ "(declare-fun I14 () Int)"
+ "(declare-fun I15 () Int)"
+ "(declare-fun |at3@5| () Int)"
+ "(declare-fun |at3@3| () Int)"
+ "(declare-fun |At5@3| () Int)"
+ "(declare-fun |At7@3| () Int)"
+ "(declare-fun |At7@5| () Int)"
+ "(declare-fun |ahead@3| () Int)"
+ "(declare-fun |ahead@2| () Int)"
+ "(declare-fun |At5@5| () Int)"
+ "(assert "
+ " (and (not (<= |ahead@2| 0))"
+ " (= |H@2| (store |H@1| |At5@3| 1))"
+ " (= |H@3| (store |H@2| 3 1))"
+ " (= |H@4| (store |H@3| 4 1))"
+ " (= |H@5| (store |H@4| 5 1))"
+ " (= |H@6| (store |H@5| 6 1))"
+ " (= |H@7| (store |H@6| 7 1))"
+ " (= |H@8| (store |H@7| 8 1))"
+ " (= |at3@3| (select |H@1| |ahead@2|))"
+ " (= |at3@5| (select |H@7| |ahead@3|))"
+ " (= I11 (+ 12 I10))"
+ " (= I13 (+ 12 I12))"
+ " (= I15 (+ 12 I14))"
+ " ))";
private static final String UGLY_ARRAY_QUERY =
"(declare-fun V () Int)"
+ "(declare-fun W () Int)"
+ "(declare-fun A () Int)"
+ "(declare-fun B () Int)"
+ "(declare-fun U () Int)"
+ "(declare-fun G () Int)"
+ "(declare-fun ARR () (Array Int Int))"
+ "(declare-fun EMPTY () (Array Int Int))"
+ "(assert "
+ " (and (> (+ V U) 0)"
+ " (not (= B (- 4)))"
+ " (= ARR (store (store (store EMPTY G B) B G) A W))"
+ " ))";
private static final String UGLY_ARRAY_QUERY_2 =
"(declare-fun A () Int)"
+ "(declare-fun B () Int)"
+ "(declare-fun ARR () (Array Int Int))"
+ "(declare-fun EMPTY () (Array Int Int))"
+ "(assert (and (= A 0) (= B 0) (= ARR (store (store EMPTY A 1) B 2))))";
private static final String SMALL_BV_FLOAT_QUERY =
"(declare-fun |f@2| () (_ FloatingPoint 8 23))"
+ "(declare-fun |p@3| () (_ BitVec 32))"
+ "(declare-fun *float@1 () (Array (_ BitVec 32) (_ FloatingPoint 8 23)))"
+ "(declare-fun |i@33| () (_ BitVec 32))"
+ "(declare-fun |Ai@| () (_ BitVec 32))"
+ "(declare-fun *unsigned_int@1 () (Array (_ BitVec 32) (_ BitVec 32)))"
+ "(assert (and (bvslt #x00000000 |Ai@|)"
+ " (bvslt #x00000000 (bvadd |Ai@| #x00000020))"
+ " (= |i@33| #x00000000)"
+ " (= |p@3| |Ai@|)"
+ " (= (select *unsigned_int@1 |Ai@|) |i@33|)"
+ " (= |f@2| (select *float@1 |p@3|))"
+ " (not (fp.eq ((_ to_fp 11 52) roundNearestTiesToEven |f@2|)"
+ " (_ +zero 11 52)))))";
private static final String SMALL_BV_FLOAT_QUERY2 =
"(declare-fun a () (_ FloatingPoint 8 23))"
+ "(declare-fun A () (Array (_ BitVec 32) (_ FloatingPoint 8 23)))"
+ "(assert (= a (select A #x00000000)))";
@Test
public void arrayTest1() throws SolverException, InterruptedException {
requireParser();
requireArrays();
for (String query :
ImmutableList.of(
SMALL_ARRAY_QUERY, MEDIUM_ARRAY_QUERY, UGLY_ARRAY_QUERY, UGLY_ARRAY_QUERY_2)) {
BooleanFormula formula = context.getFormulaManager().parse(query);
checkModelIteration(formula, false);
}
}
@Test
public void arrayTest2() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireOptimization();
requireFloats();
requireBitvectors();
// only Z3 fulfills these requirements
for (String query :
ImmutableList.of(BIG_ARRAY_QUERY, SMALL_BV_FLOAT_QUERY, SMALL_BV_FLOAT_QUERY2)) {
BooleanFormula formula = context.getFormulaManager().parse(query);
checkModelIteration(formula, true);
checkModelIteration(formula, false);
}
}
private static final String ARRAY_QUERY_INT =
"(declare-fun i () Int)"
+ "(declare-fun X () (Array Int Int))"
+ "(declare-fun Y () (Array Int Int))"
+ "(declare-fun Z () (Array Int Int))"
+ "(assert (and "
+ " (= Y (store X i 0))"
+ " (= (select Y 5) 1)"
+ " (= Z (store Y 5 2))"
+ "))";
private static final String ARRAY_QUERY_BV =
"(declare-fun v () (_ BitVec 64))"
+ "(declare-fun A () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(declare-fun B () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(declare-fun C () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(assert (and "
+ " (= B (store A v (_ bv0 32)))"
+ " (= (select B (_ bv5 64)) (_ bv1 32))"
+ " (= C (store B (_ bv5 64) (_ bv2 32)))"
+ "))";
@Test
public void arrayTest3() throws SolverException, InterruptedException {
requireParser();
requireArrays();
BooleanFormula formula = context.getFormulaManager().parse(ARRAY_QUERY_INT);
checkModelIteration(formula, false);
}
@Test
public void arrayTest4() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireBitvectors();
BooleanFormula formula = context.getFormulaManager().parse(ARRAY_QUERY_BV);
checkModelIteration(formula, false);
}
@Test
public void arrayTest5()
throws SolverException, InterruptedException, IllegalArgumentException, IOException {
requireParser();
requireArrays();
requireBitvectors();
assume()
.withMessage("Solver is quite slow for this example")
.that(solverToUse())
.isNoneOf(Solvers.PRINCESS, Solvers.Z3);
// TODO regression:
// the Z3 library was able to solve this in v4.11.2, but no longer in v4.12.1-glibc_2.27.
BooleanFormula formula =
context
.getFormulaManager()
.parse(
Files.readString(Path.of("src/org/sosy_lab/java_smt/test/SMT2_UF_and_Array.smt2")));
checkModelIteration(formula, false);
}
@Test
@SuppressWarnings("resource")
public void multiCloseTest() throws SolverException, InterruptedException {
Formula x;
BooleanFormula eq;
if (imgr != null) {
x = imgr.makeVariable("x");
eq = imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1));
} else {
// Boolector only has bitvectors
x = bvmgr.makeVariable(8, "x");
eq = bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1));
}
ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS);
try {
prover.push(eq);
assertThat(prover).isSatisfiable();
Model m = prover.getModel();
try {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
// close the model several times
} finally {
for (int i = 0; i < 10; i++) {
m.close();
}
}
} finally {
// close the prover several times
for (int i = 0; i < 10; i++) {
prover.close();
}
}
}
@Test
@SuppressWarnings("resource")
public void modelAfterSolverCloseTest() throws SolverException, InterruptedException {
ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS);
if (imgr != null) {
prover.push(imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)));
} else {
prover.push(bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1)));
}
assertThat(prover).isSatisfiable();
Model m = prover.getModel();
// close prover first
prover.close();
// try to access model, this should either fail fast or succeed
try {
if (imgr != null) {
assertThat(m.evaluate(imgr.makeVariable("x"))).isEqualTo(BigInteger.ONE);
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "x"))).isEqualTo(BigInteger.ONE);
}
} catch (IllegalStateException e) {
// ignore
} finally {
m.close();
}
}
@SuppressWarnings("resource")
@Test(expected = IllegalStateException.class)
public void testGenerateModelsOption() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment()) { // no option
assertThat(prover).isSatisfiable();
prover.getModel();
assert_().fail();
}
}
@Test(expected = IllegalStateException.class)
public void testGenerateModelsOption2() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment()) { // no option
assertThat(prover).isSatisfiable();
prover.getModelAssignments();
assert_().fail();
}
}
@Test
public void testGetSmallIntegers1() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("x")),
BigInteger.valueOf(20));
}
@Test
public void testGetSmallIntegers2() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("x"), imgr.makeNumber(1)),
BigInteger.valueOf(11));
}
@Test
public void testGetNegativeIntegers1() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(-10)),
imgr.add(imgr.makeVariable("x"), imgr.makeNumber(1)),
BigInteger.valueOf(-9));
}
@Test
public void testGetSmallIntegralRationals1() throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.add(rmgr.makeVariable("x"), rmgr.makeVariable("x")),
BigInteger.valueOf(2));
}
@Test
public void testGetRationals1() throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("1/3"))),
rmgr.divide(rmgr.makeVariable("x"), rmgr.makeNumber(2)),
Rational.ofString("1/6"));
}
@Test
public void testGetBooleans1() throws SolverException, InterruptedException {
evaluateInModel(bmgr.makeVariable("x"), bmgr.makeBoolean(true), true);
evaluateInModel(bmgr.makeVariable("x"), bmgr.makeBoolean(false), false);
evaluateInModel(
bmgr.makeVariable("x"),
bmgr.or(bmgr.makeVariable("x"), bmgr.not(bmgr.makeVariable("x"))),
true);
evaluateInModel(
bmgr.makeVariable("x"),
bmgr.and(bmgr.makeVariable("x"), bmgr.not(bmgr.makeVariable("x"))),
false);
}
@Test // (timeout = 10_000)
// TODO CVC5 crashes on making the first boolean symbol when using timeout ???.
public void testDeeplyNestedFormulaLIA() throws SolverException, InterruptedException {
requireIntegers();
testDeeplyNestedFormula(
depth -> imgr.makeVariable("i_" + depth),
var -> imgr.equal(var, imgr.makeNumber(0)),
var -> imgr.equal(var, imgr.makeNumber(1)));
}
@Test // (timeout = 10_000)
// TODO CVC5 crashes on making the first boolean symbol when using timeout ???.
public void testDeeplyNestedFormulaBV() throws SolverException, InterruptedException {
requireBitvectors();
testDeeplyNestedFormula(
depth -> bvmgr.makeVariable(4, "bv_" + depth),
var -> bvmgr.equal(var, bvmgr.makeBitvector(4, 0)),
var -> bvmgr.equal(var, bvmgr.makeBitvector(4, 1)));
}
/**
* Build a deep nesting that is easy to solve and can not be simplified by the solver. If any part
* of JavaSMT or the solver tries to analyse all branches of this formula, the runtime is
* exponential. We should avoid such a case.
*/
private <T> void testDeeplyNestedFormula(
Function<Integer, T> makeVar,
Function<T, BooleanFormula> makeEqZero,
Function<T, BooleanFormula> makeEqOne)
throws SolverException, InterruptedException {
// Warning: do never call "toString" on this formula!
BooleanFormula f = bmgr.makeVariable("basis");
for (int depth = 0; depth < 10; depth++) {
T var = makeVar.apply(depth);
f = bmgr.or(bmgr.and(f, makeEqZero.apply(var)), bmgr.and(f, makeEqOne.apply(var)));
}
// A depth of 16 results in 65.536 paths and model generation requires about 10-20 seconds if
// badly implemented.
// We expect the following model-generation to be 'fast', e.g., the 17 variables should be
// evaluated in an instant. If the time consumption is high, there is a bug in JavaSMT.
evaluateInModel(f, bmgr.makeVariable("basis"), true);
}
private void evaluateInModel(BooleanFormula constraint, Formula variable, Object expectedValue)
throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(constraint);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(variable)).isEqualTo(expectedValue);
}
}
}
}
| 94,238 | 38.200915 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/NonLinearArithmeticTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormulaManager;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager.NonLinearArithmetic;
@RunWith(Parameterized.class)
public class NonLinearArithmeticTest<T extends NumeralFormula> extends SolverBasedTest0 {
// Boolector, CVC4, SMTInterpol and MathSAT5 do not fully support non-linear arithmetic
// (though SMTInterpol and MathSAT5 support some parts)
static final ImmutableSet<Solvers> SOLVER_WITHOUT_NONLINEAR_ARITHMETIC =
ImmutableSet.of(
Solvers.SMTINTERPOL, Solvers.MATHSAT5, Solvers.BOOLECTOR, Solvers.CVC4, Solvers.YICES2);
@Parameters(name = "{0} {1} {2}")
public static Iterable<Object[]> getAllSolversAndTheories() {
return Lists.cartesianProduct(
Arrays.asList(Solvers.values()),
ImmutableList.of(FormulaType.IntegerType, FormulaType.RationalType),
Arrays.asList(NonLinearArithmetic.values()))
.stream()
.map(List::toArray)
.collect(toImmutableList());
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Parameter(1)
public FormulaType<?> formulaType;
private NumeralFormulaManager<T, T> nmgr;
@SuppressWarnings("unchecked")
@Before
public void chooseNumeralFormulaManager() {
if (formulaType.isIntegerType()) {
requireIntegers();
nmgr = (NumeralFormulaManager<T, T>) imgr;
} else if (formulaType.isRationalType()) {
requireRationals();
nmgr = (NumeralFormulaManager<T, T>) rmgr;
} else {
throw new AssertionError();
}
}
@Parameter(2)
public NonLinearArithmetic nonLinearArithmetic;
@Override
protected ConfigurationBuilder createTestConfigBuilder() {
return super.createTestConfigBuilder()
.setOption("solver.nonLinearArithmetic", nonLinearArithmetic.name());
}
private T handleExpectedException(Supplier<T> supplier) {
try {
return supplier.get();
} catch (UnsupportedOperationException e) {
if (nonLinearArithmetic == NonLinearArithmetic.USE
&& SOLVER_WITHOUT_NONLINEAR_ARITHMETIC.contains(solver)) {
throw new AssumptionViolatedException(
"Expected UnsupportedOperationException was thrown correctly");
}
throw e;
}
}
private void assertExpectedUnsatifiabilityForNonLinearArithmetic(BooleanFormula f)
throws SolverException, InterruptedException {
if (nonLinearArithmetic == NonLinearArithmetic.USE
|| (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK
&& !SOLVER_WITHOUT_NONLINEAR_ARITHMETIC.contains(solver))) {
assertThatFormula(f).isUnsatisfiable();
} else {
assertThatFormula(f).isSatisfiable();
}
}
@Test
public void testLinearMultiplication() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
nmgr.equal(a, nmgr.multiply(nmgr.makeNumber(2), nmgr.makeNumber(3))),
nmgr.equal(nmgr.makeNumber(2 * 3 * 5), nmgr.multiply(a, nmgr.makeNumber(5))),
nmgr.equal(nmgr.makeNumber(2 * 3 * 5), nmgr.multiply(nmgr.makeNumber(5), a)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testLinearMultiplicationUnsatisfiable() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
nmgr.equal(a, nmgr.multiply(nmgr.makeNumber(2), nmgr.makeNumber(3))),
bmgr.xor(
nmgr.equal(nmgr.makeNumber(2 * 3 * 5), nmgr.multiply(a, nmgr.makeNumber(5))),
nmgr.equal(nmgr.makeNumber(2 * 3 * 5), nmgr.multiply(nmgr.makeNumber(5), a))));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testMultiplicationOfVariables() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
T b = nmgr.makeVariable("b");
T c = nmgr.makeVariable("c");
BooleanFormula f =
bmgr.and(
nmgr.equal(c, handleExpectedException(() -> nmgr.multiply(a, b))),
nmgr.equal(c, nmgr.makeNumber(2 * 3)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testMultiplicationOfVariablesUnsatisfiable()
throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
T b = nmgr.makeVariable("b");
T c = nmgr.makeVariable("c");
BooleanFormula f =
bmgr.and(
nmgr.equal(handleExpectedException(() -> nmgr.multiply(a, b)), c),
nmgr.equal(a, nmgr.makeNumber(3)),
nmgr.equal(b, nmgr.makeNumber(5)),
bmgr.not(nmgr.equal(c, nmgr.makeNumber(15))));
if (solver == Solvers.MATHSAT5
&& nonLinearArithmetic != NonLinearArithmetic.APPROXIMATE_ALWAYS) {
// MathSAT supports non-linear multiplication
assertThatFormula(f).isUnsatisfiable();
} else {
assertExpectedUnsatifiabilityForNonLinearArithmetic(f);
}
}
@Test
public void testDivisionByConstant() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
nmgr.equal(nmgr.makeNumber(2 * 3), a),
nmgr.equal(nmgr.divide(a, nmgr.makeNumber(3)), nmgr.makeNumber(2)),
nmgr.equal(nmgr.divide(a, nmgr.makeNumber(2)), nmgr.makeNumber(3)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testDivisionByZero() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support division by zero", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.YICES2);
T a = nmgr.makeVariable("a");
T b = nmgr.makeVariable("b");
T zero = nmgr.makeNumber(0);
BooleanFormula f =
bmgr.and(
nmgr.equal(nmgr.divide(a, zero), nmgr.makeNumber(2)),
nmgr.equal(nmgr.divide(b, zero), nmgr.makeNumber(4)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testDivisionByConstantUnsatisfiable() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
nmgr.equal(a, nmgr.makeNumber(2 * 3)),
bmgr.xor(
nmgr.equal(nmgr.divide(a, nmgr.makeNumber(3)), nmgr.makeNumber(2)),
nmgr.equal(nmgr.divide(a, nmgr.makeNumber(2)), nmgr.makeNumber(3))));
if (formulaType.equals(FormulaType.IntegerType)
&& nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_ALWAYS) {
// Integer division is always non-linear due to rounding rules
assertThatFormula(f).isSatisfiable();
} else {
assertThatFormula(f).isUnsatisfiable();
}
}
@Test
public void testDivision() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
// (a == 2) && (3 == 6 / a)
BooleanFormula f =
bmgr.and(
nmgr.equal(a, nmgr.makeNumber(2)),
nmgr.equal(
nmgr.makeNumber(3),
handleExpectedException(() -> nmgr.divide(nmgr.makeNumber(2 * 3), a))));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testDivisionUnsatisfiable() throws SolverException, InterruptedException {
T a = nmgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
bmgr.not(nmgr.equal(a, nmgr.makeNumber(2))),
bmgr.not(nmgr.equal(a, nmgr.makeNumber(0))), // some solver produce model a=0 otherwise
nmgr.equal(
nmgr.makeNumber(3),
handleExpectedException(() -> nmgr.divide(nmgr.makeNumber(2 * 3), a))));
if (ImmutableSet.of(Solvers.MATHSAT5, Solvers.CVC4).contains(solver)
&& nonLinearArithmetic != NonLinearArithmetic.APPROXIMATE_ALWAYS) {
// some solvers support non-linear multiplication (partially)
assertThatFormula(f).isUnsatisfiable();
} else {
assertExpectedUnsatifiabilityForNonLinearArithmetic(f);
}
}
}
| 9,220 | 33.02583 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/NonLinearArithmeticWithModuloTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.junit.AssumptionViolatedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager.NonLinearArithmetic;
@RunWith(Parameterized.class)
public class NonLinearArithmeticWithModuloTest extends SolverBasedTest0 {
@Parameters(name = "{0} {1}")
public static Iterable<Object[]> getAllSolversAndTheories() {
return Lists.cartesianProduct(
Arrays.asList(Solvers.values()), Arrays.asList(NonLinearArithmetic.values()))
.stream()
.map(List::toArray)
.collect(toImmutableList());
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Parameter(1)
public NonLinearArithmetic nonLinearArithmetic;
@Override
protected ConfigurationBuilder createTestConfigBuilder() {
return super.createTestConfigBuilder()
.setOption("solver.nonLinearArithmetic", nonLinearArithmetic.name());
}
private IntegerFormula handleExpectedException(Supplier<IntegerFormula> supplier) {
try {
return supplier.get();
} catch (UnsupportedOperationException e) {
if (nonLinearArithmetic == NonLinearArithmetic.USE
&& NonLinearArithmeticTest.SOLVER_WITHOUT_NONLINEAR_ARITHMETIC.contains(solver)) {
throw new AssumptionViolatedException(
"Expected UnsupportedOperationException was thrown correctly");
}
throw e;
}
}
private void assertExpectedUnsatifiabilityForNonLinearArithmetic(BooleanFormula f)
throws SolverException, InterruptedException {
if (nonLinearArithmetic == NonLinearArithmetic.USE
|| (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK
&& !NonLinearArithmeticTest.SOLVER_WITHOUT_NONLINEAR_ARITHMETIC.contains(solver))) {
assertThatFormula(f).isUnsatisfiable();
} else {
assertThatFormula(f).isSatisfiable();
}
}
@Test
public void testModuloConstant() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
imgr.equal(a, imgr.makeNumber(3)),
imgr.equal(
imgr.makeNumber(1),
handleExpectedException(() -> imgr.modulo(a, imgr.makeNumber(2)))));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testModuloConstantUnsatisfiable() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
imgr.equal(a, imgr.makeNumber(5)),
imgr.equal(
imgr.makeNumber(1),
handleExpectedException(() -> imgr.modulo(a, imgr.makeNumber(3)))));
if (ImmutableSet.of(Solvers.SMTINTERPOL, Solvers.CVC4, Solvers.YICES2).contains(solver)
&& nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK) {
// some solvers support modulo with constants
assertThatFormula(f).isUnsatisfiable();
} else {
assertExpectedUnsatifiabilityForNonLinearArithmetic(f);
}
}
@Test
public void testModulo() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
imgr.equal(a, imgr.makeNumber(2)),
imgr.equal(
imgr.makeNumber(1),
handleExpectedException(() -> imgr.modulo(imgr.makeNumber(3), a))));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testModuloUnsatisfiable() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
BooleanFormula f =
bmgr.and(
imgr.equal(a, imgr.makeNumber(3)),
imgr.equal(
imgr.makeNumber(1),
handleExpectedException(() -> imgr.modulo(imgr.makeNumber(5), a))));
if (Solvers.CVC4 == solver && nonLinearArithmetic != NonLinearArithmetic.APPROXIMATE_ALWAYS) {
// some solvers support non-linear multiplication (partially)
assertThatFormula(f).isUnsatisfiable();
} else {
assertExpectedUnsatifiabilityForNonLinearArithmetic(f);
}
}
}
| 5,233 | 32.33758 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/NumeralFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
public class NumeralFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void distinctTest() throws SolverException, InterruptedException {
requireIntegers();
List<IntegerFormula> symbols = new ArrayList<>();
for (int i = 0; i < 5; i++) {
IntegerFormula symbol = imgr.makeVariable("x" + i);
symbols.add(symbol);
}
assertThatFormula(imgr.distinct(symbols)).isSatisfiable();
}
@Test
public void distinctTest2() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula four = imgr.makeNumber(4);
List<IntegerFormula> symbols = new ArrayList<>();
List<BooleanFormula> constraints = new ArrayList<>();
for (int i = 0; i < 5; i++) {
IntegerFormula symbol = imgr.makeVariable("x" + i);
symbols.add(symbol);
constraints.add(imgr.lessOrEquals(zero, symbol));
constraints.add(imgr.lessOrEquals(symbol, four));
}
assertThatFormula(bmgr.and(imgr.distinct(symbols), bmgr.and(constraints))).isSatisfiable();
}
@Test
public void distinctTest3() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula four = imgr.makeNumber(4);
List<IntegerFormula> symbols = new ArrayList<>();
List<BooleanFormula> constraints = new ArrayList<>();
for (int i = 0; i < 5; i++) {
IntegerFormula symbol = imgr.makeVariable("x" + i);
symbols.add(symbol);
constraints.add(imgr.lessOrEquals(zero, symbol));
constraints.add(imgr.lessThan(symbol, four));
}
assertThatFormula(bmgr.and(imgr.distinct(symbols), bmgr.and(constraints))).isUnsatisfiable();
}
@SuppressWarnings("CheckReturnValue")
@Test(expected = Exception.class)
public void failOnInvalidString() {
requireIntegers();
imgr.makeNumber("a");
assert_().fail();
}
@SuppressWarnings("CheckReturnValue")
@Test
public void testSubTypes() {
requireIntegers();
requireRationals();
IntegerFormula a = imgr.makeVariable("a");
RationalFormula r = rmgr.makeVariable("r");
List<FormulaType<?>> argTypes =
ImmutableList.of(FormulaType.RationalType, FormulaType.RationalType);
FunctionDeclaration<IntegerFormula> ufDecl =
fmgr.declareUF("uf", FormulaType.IntegerType, argTypes);
IntegerFormula uf = fmgr.callUF(ufDecl, a, r);
mgr.visit(
bmgr.and(rmgr.equal(uf, imgr.makeNumber(0))),
new DefaultFormulaVisitor<Void>() {
@Override
public Void visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pDeclaration) {
if ("uf".equals(pDeclaration.getName())) {
checkUf(pDeclaration);
} else {
checkIntEq(pDeclaration);
}
return null;
}
private void checkUf(FunctionDeclaration<?> pDeclaration) {
assertThat(pDeclaration.getArgumentTypes()).isEqualTo(argTypes);
FunctionDeclaration<?> ufDecl2 =
fmgr.declareUF("uf", pDeclaration.getType(), pDeclaration.getArgumentTypes());
Formula uf2 = fmgr.callUF(ufDecl2, a, r);
assertThat(uf2).isEqualTo(uf);
fmgr.callUF(ufDecl2, r, r);
}
private void checkIntEq(FunctionDeclaration<?> pDeclaration) {
assertThat(pDeclaration.getArgumentTypes())
.containsExactly(FormulaType.IntegerType, FormulaType.IntegerType)
.inOrder();
}
@Override
protected Void visitDefault(Formula pF) {
return null;
}
});
}
}
| 4,664 | 34.884615 | 97 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/OptimizationTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.Range;
import java.math.BigInteger;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment.OptStatus;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
public class OptimizationTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Override
protected ConfigurationBuilder createTestConfigBuilder() {
return super.createTestConfigBuilder().setOption("solver.mathsat5.loadOptimathsat5", "true");
}
@Before
public void skipUnsupportedSolvers() {
requireOptimization();
}
@Test
public void testUnbounded() throws SolverException, InterruptedException {
requireRationals();
try (OptimizationProverEnvironment prover = context.newOptimizationProverEnvironment()) {
RationalFormula x = rmgr.makeVariable("x");
RationalFormula obj = rmgr.makeVariable("obj");
prover.addConstraint(
bmgr.and(rmgr.greaterOrEquals(x, rmgr.makeNumber("10")), rmgr.equal(x, obj)));
int handle = prover.maximize(obj);
OptStatus response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
assertThat(prover.upper(handle, Rational.ZERO)).isEmpty();
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void testUnfeasible() throws SolverException, InterruptedException {
requireRationals();
try (OptimizationProverEnvironment prover = context.newOptimizationProverEnvironment()) {
RationalFormula x = rmgr.makeVariable("x");
RationalFormula y = rmgr.makeVariable("y");
prover.addConstraint(bmgr.and(rmgr.lessThan(x, y), rmgr.greaterThan(x, y)));
prover.maximize(x);
OptStatus response = prover.check();
assertThat(response).isEqualTo(OptStatus.UNSAT);
}
}
@Test
public void testOptimal() throws SolverException, InterruptedException {
try (OptimizationProverEnvironment prover =
context.newOptimizationProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula obj = imgr.makeVariable("obj");
/*
int x, y, obj
x <= 10
y <= 15
obj = x + y
x - y >= 1
*/
prover.addConstraint(
bmgr.and(
imgr.lessOrEquals(x, imgr.makeNumber(10)),
imgr.lessOrEquals(y, imgr.makeNumber(15)),
imgr.equal(obj, imgr.add(x, y)),
imgr.greaterOrEquals(imgr.subtract(x, y), imgr.makeNumber(1))));
int handle = prover.maximize(obj);
// Maximize for x.
OptStatus response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
// Check the value.
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.ofString("19"));
try (Model model = prover.getModel()) {
BigInteger xValue = model.evaluate(x);
BigInteger objValue = model.evaluate(obj);
BigInteger yValue = model.evaluate(y);
assertThat(objValue).isEqualTo(BigInteger.valueOf(19));
assertThat(xValue).isEqualTo(BigInteger.valueOf(10));
assertThat(yValue).isEqualTo(BigInteger.valueOf(9));
}
}
}
@Test(timeout = 20_000)
public void testSwitchingObjectives() throws SolverException, InterruptedException {
requireRationals();
if (solverToUse() == Solvers.MATHSAT5) {
// see https://github.com/sosy-lab/java-smt/issues/233
assume()
.withMessage("OptiMathSAT 1.7.2 has a bug with switching objectives")
.that(context.getVersion())
.doesNotContain("MathSAT5 version 1.7.2");
assume()
.withMessage("OptiMathSAT 1.7.3 has a bug with switching objectives")
.that(context.getVersion())
.doesNotContain("MathSAT5 version 1.7.3");
}
try (OptimizationProverEnvironment prover = context.newOptimizationProverEnvironment()) {
RationalFormula x = rmgr.makeVariable("x");
RationalFormula y = rmgr.makeVariable("y");
RationalFormula obj = rmgr.makeVariable("obj");
prover.push();
/*
real x, y, obj
x <= 10
y <= 15
obj = x + y
x - y >= 1
*/
prover.addConstraint(
bmgr.and(
rmgr.lessOrEquals(x, rmgr.makeNumber(10)),
rmgr.lessOrEquals(y, rmgr.makeNumber(15)),
rmgr.equal(obj, rmgr.add(x, y)),
rmgr.greaterOrEquals(rmgr.subtract(x, y), rmgr.makeNumber(1))));
OptStatus response;
prover.push();
int handle = prover.maximize(obj);
response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.ofString("19"));
prover.pop();
prover.push();
handle = prover.maximize(x);
response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.ofString("10"));
prover.pop();
prover.push();
handle = prover.maximize(rmgr.makeVariable("y"));
response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.ofString("9"));
prover.pop();
}
}
@Test
public void testStrictConstraint() throws SolverException, InterruptedException {
requireRationals();
try (OptimizationProverEnvironment prover = context.newOptimizationProverEnvironment()) {
RationalFormula x = rmgr.makeVariable("x");
// assume (x < 1)
prover.addConstraint(rmgr.lessThan(x, rmgr.makeNumber(1)));
int handle = prover.maximize(x);
assertThat(prover.check()).isEqualTo(OptStatus.OPT);
// let's check how close we can get to value 1.
for (long i : new long[] {1, 10, 100, 1000, 10000, 100000000L, 1000000000000L}) {
long largeI = i * 1000000L; // increase precision
Rational epsilon = Rational.ofLongs(1, largeI);
Rational lowerBoundOfRange = Rational.ONE.minus(epsilon).minus(epsilon);
Rational approximation = prover.upper(handle, epsilon).orElseThrow();
assertThat(approximation).isIn(Range.closedOpen(lowerBoundOfRange, Rational.ONE));
}
// OptiMathSAT5 has at least an epsilon of 1/1000000. It does not allow larger values.
assume()
.withMessage("Solver %s does not support large epsilons", solverToUse())
.that(solver)
.isNotEqualTo(Solvers.MATHSAT5);
for (long i : new long[] {1, 10, 100, 1000, 10000, 100000}) {
Rational epsilon = Rational.ofLongs(1, i);
Rational lowerBoundOfRange = Rational.ONE.minus(epsilon).minus(epsilon);
Rational approximation = prover.upper(handle, epsilon).orElseThrow();
assertThat(approximation).isIn(Range.closedOpen(lowerBoundOfRange, Rational.ONE));
}
// check strict value
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.of(1));
}
}
}
| 7,974 | 35.582569 | 97 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/PrettyPrinterTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.utils.PrettyPrinter;
import org.sosy_lab.java_smt.utils.PrettyPrinter.PrinterOption;
public class PrettyPrinterTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private PrettyPrinter pp;
private static final String VARS =
"(declare-fun x () Int)"
+ "(declare-fun xx () Int)"
+ "(declare-fun y () Real)"
+ "(declare-fun yy () Real)"
+ "(declare-fun arr () (Array Int Int))"
+ "(declare-fun arr2 () (Array Int Int))"
+ "(declare-fun foo (Int) Int)"
+ "(declare-fun bar (Real) Real)";
private static final String QUERY_1 = "(assert (and (= (select arr x) (foo 3)) (< x xx)))";
@Before
public void init() {
pp = new PrettyPrinter(context.getFormulaManager());
}
@Test
public void testPrettyPrintOnlyBoolean() {
requireParser();
String expected;
switch (solverToUse()) {
case MATHSAT5:
expected =
"(`and`\n"
+ " (`=_int` (`read_int_int` arr x) (foo 3))\n"
+ " (`not`\n"
+ " (`<=_int` xx x)\n"
+ " )\n"
+ ")";
break;
case PRINCESS:
expected =
"(And\n"
+ " (= (select arr x) (foo 3))\n"
+ " (GeqZero (+ (+ xx (* -1 x)) -1))\n"
+ ")";
break;
default:
expected = "(and\n" + " (= (select arr x) (foo 3))\n" + " (< x xx)\n" + ")";
}
expected = expected.replace("\n", System.lineSeparator());
assertThat(
pp.formulaToString(
mgr.parse(VARS + QUERY_1), PrinterOption.SPLIT_ONLY_BOOLEAN_OPERATIONS))
.isEqualTo(expected);
}
@Test
public void testPrettyPrintAll() {
requireParser();
String expected;
switch (solverToUse()) {
case MATHSAT5:
expected =
"(`and`\n"
+ " (`=_int`\n"
+ " (`read_int_int`\n"
+ " arr\n"
+ " x\n"
+ " )\n"
+ " (foo\n"
+ " 3\n"
+ " )\n"
+ " )\n"
+ " (`not`\n"
+ " (`<=_int`\n"
+ " xx\n"
+ " x\n"
+ " )\n"
+ " )\n"
+ ")";
break;
case PRINCESS:
expected =
"(And\n"
+ " (=\n"
+ " (select\n"
+ " arr\n"
+ " x\n"
+ " )\n"
+ " (foo\n"
+ " 3\n"
+ " )\n"
+ " )\n"
+ " (GeqZero\n"
+ " (+\n"
+ " (+\n"
+ " xx\n"
+ " (*\n"
+ " -1\n"
+ " x\n"
+ " )\n"
+ " )\n"
+ " -1\n"
+ " )\n"
+ " )\n"
+ ")";
break;
default:
expected =
"(and\n"
+ " (=\n"
+ " (select\n"
+ " arr\n"
+ " x\n"
+ " )\n"
+ " (foo\n"
+ " 3\n"
+ " )\n"
+ " )\n"
+ " (<\n"
+ " x\n"
+ " xx\n"
+ " )\n"
+ ")";
}
expected = expected.replace("\n", System.lineSeparator());
assertThat(pp.formulaToString(mgr.parse(VARS + QUERY_1))).isEqualTo(expected);
}
@Test
public void testDotOnlyBoolean() {
requireParser();
String expected;
switch (solverToUse()) {
case MATHSAT5:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"`and`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " 2 [label=\"`not`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"orange\"];\n"
+ " 2 -> 3 [label=\"\"];\n"
+ " { rank=same;\n"
+ " 3 [label=\"(`<=_int` xx x)\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 1 [label=\"(`=_int` (`read_int_int` arr x) (foo 3))\", shape=\"rectangle\","
+ " style=\"filled\", fillcolor=\"white\"];\n"
+ " }\n"
+ "}";
break;
case PRINCESS:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"And\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " { rank=same;\n"
+ " 2 [label=\"(((xx + -1 * x) + -1) >= 0)\", shape=\"rectangle\","
+ " style=\"filled\", fillcolor=\"white\"];\n"
+ " 1 [label=\"(select(arr, x) = foo(3))\", shape=\"rectangle\","
+ " style=\"filled\", fillcolor=\"white\"];\n"
+ " }\n"
+ "}";
break;
default:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"and\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " { rank=same;\n"
+ " 2 [label=\"(< x xx)\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 1 [label=\"(= (select arr x) (foo 3))\", shape=\"rectangle\","
+ " style=\"filled\", fillcolor=\"white\"];\n"
+ " }\n"
+ "}";
}
expected = expected.replace("\n", System.lineSeparator());
assertThat(
pp.formulaToDot(mgr.parse(VARS + QUERY_1), PrinterOption.SPLIT_ONLY_BOOLEAN_OPERATIONS))
.isEqualTo(expected);
}
@Test
public void testDotAll() {
requireParser();
String expected;
switch (solverToUse()) {
case MATHSAT5:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"`and`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " 2 [label=\"`not`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"orange\"];\n"
+ " 2 -> 3 [label=\"\"];\n"
+ " 3 [label=\"`<=_int`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 3 -> 4 [label=\"0\"];\n"
+ " 3 -> 5 [label=\"1\"];\n"
+ " 5 [label=\"x\", shape=\"rectangle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 4 [label=\"xx\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 1 [label=\"`=_int`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 1 -> 6 [label=\"0\"];\n"
+ " 1 -> 7 [label=\"1\"];\n"
+ " 7 [label=\"foo\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 7 -> 8 [label=\"0\"];\n"
+ " 8 [label=\"3\", shape=\"rectangle\", style=\"filled\", fillcolor=\"grey\"];\n"
+ " 6 [label=\"`read_int_int`\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 6 -> 9 [label=\"0\"];\n"
+ " 6 -> 5 [label=\"1\"];\n"
+ " 9 [label=\"arr\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ "}";
break;
case PRINCESS:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"And\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " 2 [label=\"GeqZero\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 2 -> 3 [label=\"0\"];\n"
+ " 3 [label=\"+\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 3 -> 4 [label=\"0\"];\n"
+ " 3 -> 5 [label=\"1\"];\n"
+ " 5 [label=\"-1\", shape=\"rectangle\", style=\"filled\", fillcolor=\"grey\"];\n"
+ " 4 [label=\"+\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 4 -> 6 [label=\"0\"];\n"
+ " 4 -> 7 [label=\"1\"];\n"
+ " 7 [label=\"*\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 7 -> 5 [label=\"0\"];\n"
+ " 7 -> 8 [label=\"1\"];\n"
+ " 8 [label=\"x\", shape=\"rectangle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 6 [label=\"xx\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 1 [label=\"=\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 1 -> 9 [label=\"0\"];\n"
+ " 1 -> 10 [label=\"1\"];\n"
+ " 10 [label=\"foo\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 10 -> 11 [label=\"0\"];\n"
+ " 11 [label=\"3\", shape=\"rectangle\", style=\"filled\", fillcolor=\"grey\"];\n"
+ " 9 [label=\"select\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 9 -> 12 [label=\"0\"];\n"
+ " 9 -> 8 [label=\"1\"];\n"
+ " 12 [label=\"arr\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ "}";
break;
default:
expected =
"digraph SMT {\n"
+ " rankdir=LR\n"
+ " 0 [label=\"and\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"lightblue\"];\n"
+ " 0 -> 1 [label=\"\"];\n"
+ " 0 -> 2 [label=\"\"];\n"
+ " 2 [label=\"<\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 2 -> 3 [label=\"0\"];\n"
+ " 2 -> 4 [label=\"1\"];\n"
+ " 4 [label=\"xx\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 3 [label=\"x\", shape=\"rectangle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 1 [label=\"=\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 1 -> 5 [label=\"0\"];\n"
+ " 1 -> 6 [label=\"1\"];\n"
+ " 6 [label=\"foo\", shape=\"circle\", style=\"filled\", fillcolor=\"white\"];\n"
+ " 6 -> 7 [label=\"0\"];\n"
+ " 7 [label=\"3\", shape=\"rectangle\", style=\"filled\", fillcolor=\"grey\"];\n"
+ " 5 [label=\"select\", shape=\"circle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ " 5 -> 8 [label=\"0\"];\n"
+ " 5 -> 3 [label=\"1\"];\n"
+ " 8 [label=\"arr\", shape=\"rectangle\", style=\"filled\","
+ " fillcolor=\"white\"];\n"
+ "}";
}
expected = expected.replace("\n", System.lineSeparator());
assertThat(pp.formulaToDot(mgr.parse(VARS + QUERY_1))).isEqualTo(expected);
}
}
| 12,556 | 39.118211 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ProverEnvironmentSubject.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assert_;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.truth.Fact;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StandardSubjectBuilder;
import com.google.common.truth.Subject;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.List;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverException;
/**
* {@link Subject} subclass for testing assertions about ProverEnvironments with Truth (allows using
* <code>assert_().about(...).that(stack).isUnsatisfiable()</code> etc.).
*
* <p>For a test use {@link SolverBasedTest0#assertThatEnvironment(BasicProverEnvironment)}, or
* {@link StandardSubjectBuilder#about(com.google.common.truth.Subject.Factory)} and {@link
* #proverEnvironments()}.
*/
@SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS")
public final class ProverEnvironmentSubject extends Subject {
private final BasicProverEnvironment<?> stackUnderTest;
private ProverEnvironmentSubject(FailureMetadata pMetadata, BasicProverEnvironment<?> pStack) {
super(pMetadata, pStack);
stackUnderTest = Preconditions.checkNotNull(pStack);
}
/**
* Use this for checking assertions about ProverEnvironments with Truth: <code>
* assert_().about(proverEnvironments()).that(stack).is...()</code>.
*/
public static Subject.Factory<ProverEnvironmentSubject, BasicProverEnvironment<?>>
proverEnvironments() {
return ProverEnvironmentSubject::new;
}
/**
* Use this for checking assertions about ProverEnvironments with Truth: <code>
* assertThat(stack).is...()</code>.
*/
public static ProverEnvironmentSubject assertThat(BasicProverEnvironment<?> prover) {
return assert_().about(proverEnvironments()).that(prover);
}
/**
* Check that the subject stack is unsatisfiable. Will show a model (satisfying assignment) on
* failure.
*/
public void isUnsatisfiable() throws SolverException, InterruptedException {
if (stackUnderTest.isUnsat()) {
return; // success
}
// get model for failure message
try (Model model = stackUnderTest.getModel()) {
failWithoutActual(
Fact.fact("expected to be", "unsatisfiable"),
Fact.fact("but was", stackUnderTest),
Fact.fact("which is", "satisfiable"),
Fact.fact("which has model", model));
}
}
/** Check that the subject stack is satisfiable. Will show an unsat core on failure. */
public void isSatisfiable() throws SolverException, InterruptedException {
if (!stackUnderTest.isUnsat()) {
return; // success
}
// get unsat core for failure message if possible
if (stackUnderTest instanceof ProverEnvironment) {
try {
final List<BooleanFormula> unsatCore = stackUnderTest.getUnsatCore();
if (!unsatCore.isEmpty()) {
failWithoutActual(
Fact.fact("expected to be", "satisfiable"),
Fact.fact("but was", stackUnderTest),
Fact.fact("which is", "unsatisfiable"),
Fact.fact("with unsat core", Joiner.on('\n').join(unsatCore)));
return;
}
} catch (IllegalArgumentException ignored) {
// Skip if unsat core generation is disabled.
}
}
failWithActual(Fact.fact("expected to be", "satisfiable"));
}
}
| 3,856 | 35.386792 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ProverEnvironmentSubjectTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.ExpectFailure.assertThat;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.proverEnvironments;
import com.google.common.base.Throwables;
import com.google.common.truth.ExpectFailure;
import com.google.common.truth.ExpectFailure.SimpleSubjectBuilderCallback;
import com.google.common.truth.SimpleSubjectBuilder;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
public class ProverEnvironmentSubjectTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private BooleanFormula simpleFormula;
private BooleanFormula contradiction;
@Before
public void setupFormulas() {
if (imgr != null) {
simpleFormula = imgr.equal(imgr.makeVariable("a"), imgr.makeNumber(1));
contradiction =
bmgr.and(simpleFormula, imgr.equal(imgr.makeVariable("a"), imgr.makeNumber(2)));
} else {
simpleFormula = bvmgr.equal(bvmgr.makeVariable(2, "a"), bvmgr.makeBitvector(2, 1));
contradiction =
bmgr.and(
simpleFormula, bvmgr.equal(bvmgr.makeVariable(2, "a"), bvmgr.makeBitvector(2, 2)));
}
}
@Test
public void testIsSatisfiableYes() throws SolverException, InterruptedException {
try (ProverEnvironment env = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
env.push(simpleFormula);
assertThatEnvironment(env).isSatisfiable();
}
}
@Test
public void testIsSatisfiableNo() throws InterruptedException {
requireUnsatCore();
try (ProverEnvironment env =
context.newProverEnvironment(
ProverOptions.GENERATE_MODELS, ProverOptions.GENERATE_UNSAT_CORE)) {
env.push(contradiction);
AssertionError failure = expectFailure(whenTesting -> whenTesting.that(env).isSatisfiable());
assertThat(failure).factValue("with unsat core").isNotEmpty();
}
}
@Test
public void testIsUnsatisfiableYes() throws SolverException, InterruptedException {
try (ProverEnvironment env = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
env.push(contradiction);
assertThatEnvironment(env).isUnsatisfiable();
}
}
@Test
public void testIsUnsatisfiableNo() throws InterruptedException {
requireModel();
try (ProverEnvironment env = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
env.push(simpleFormula);
AssertionError failure =
expectFailure(whenTesting -> whenTesting.that(env).isUnsatisfiable());
assertThat(failure).factValue("which has model").isNotEmpty();
}
}
private AssertionError expectFailure(ExpectFailureCallback expectFailureCallback) {
return ExpectFailure.expectFailureAbout(proverEnvironments(), expectFailureCallback);
}
/** Variant of {@link SimpleSubjectBuilderCallback} that allows checked exception. */
private interface ExpectFailureCallback
extends SimpleSubjectBuilderCallback<ProverEnvironmentSubject, BasicProverEnvironment<?>> {
void invokeAssertionUnchecked(
SimpleSubjectBuilder<ProverEnvironmentSubject, BasicProverEnvironment<?>> pWhenTesting)
throws Exception;
@Override
default void invokeAssertion(
SimpleSubjectBuilder<ProverEnvironmentSubject, BasicProverEnvironment<?>> pWhenTesting) {
try {
invokeAssertionUnchecked(pWhenTesting);
} catch (Exception e) {
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
}
}
| 3,998 | 36.027778 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/ProverEnvironmentTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.BOOLECTOR;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.CVC4;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.CVC5;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.MATHSAT5;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.PRINCESS;
import static org.sosy_lab.java_smt.SolverContextFactory.Solvers.Z3;
import static org.sosy_lab.java_smt.api.SolverContext.ProverOptions.GENERATE_UNSAT_CORE;
import static org.sosy_lab.java_smt.api.SolverContext.ProverOptions.GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
public class ProverEnvironmentTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void assumptionsTest() throws SolverException, InterruptedException {
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c = bmgr.makeVariable("c");
try (ProverEnvironment pe = context.newProverEnvironment()) {
pe.push();
pe.addConstraint(bmgr.or(b, bmgr.makeBoolean(false)));
pe.addConstraint(c);
assertThat(pe.isUnsat()).isFalse();
assertThat(pe.isUnsatWithAssumptions(ImmutableList.of(bmgr.not(b)))).isTrue();
assertThat(pe.isUnsatWithAssumptions(ImmutableList.of(b))).isFalse();
}
}
@Test
public void assumptionsWithModelTest() throws SolverException, InterruptedException {
assume()
.withMessage("MathSAT can't construct models for SAT check with assumptions")
.that(solver)
.isNotEqualTo(MATHSAT5);
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c = bmgr.makeVariable("c");
try (ProverEnvironment pe = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
pe.push();
pe.addConstraint(bmgr.or(b, bmgr.makeBoolean(false)));
pe.addConstraint(c);
assertThat(pe.isUnsat()).isFalse();
assertThat(pe.isUnsatWithAssumptions(ImmutableList.of(bmgr.not(b)))).isTrue();
assertThat(pe.isUnsatWithAssumptions(ImmutableList.of(b))).isFalse();
try (Model m = pe.getModel()) {
assertThat(m.evaluate(c)).isTrue();
}
}
}
@Test
public void unsatCoreTest() throws SolverException, InterruptedException {
// Boolector does not support unsat core
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
try (BasicProverEnvironment<?> pe = context.newProverEnvironment(GENERATE_UNSAT_CORE)) {
unsatCoreTest0(pe);
}
}
@Test
public void unsatCoreTestForInterpolation() throws SolverException, InterruptedException {
requireInterpolation();
try (BasicProverEnvironment<?> pe =
context.newProverEnvironmentWithInterpolation(GENERATE_UNSAT_CORE)) {
unsatCoreTest0(pe);
}
}
@Test
public void unsatCoreTestForOptimizationProver() throws SolverException, InterruptedException {
requireOptimization();
// Z3 and Boolector do not implement unsat core for optimization
assume().that(solverToUse()).isNoneOf(Z3, BOOLECTOR);
try (BasicProverEnvironment<?> pe =
context.newOptimizationProverEnvironment(GENERATE_UNSAT_CORE)) {
unsatCoreTest0(pe);
}
}
private void unsatCoreTest0(BasicProverEnvironment<?> pe)
throws InterruptedException, SolverException {
pe.push();
pe.addConstraint(imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)));
pe.addConstraint(imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(2)));
pe.addConstraint(imgr.equal(imgr.makeVariable("y"), imgr.makeNumber(2)));
assertThat(pe).isUnsatisfiable();
List<BooleanFormula> unsatCore = pe.getUnsatCore();
assertThat(unsatCore)
.containsExactly(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(2)),
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)));
}
@Test
public void unsatCoreWithAssumptionsNullTest() {
assume()
.withMessage(
"Solver %s does not support unsat core generation over assumptions", solverToUse())
.that(solverToUse())
.isNoneOf(PRINCESS, BOOLECTOR, CVC4, CVC5);
try (ProverEnvironment pe =
context.newProverEnvironment(GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS)) {
assertThrows(NullPointerException.class, () -> pe.unsatCoreOverAssumptions(null));
}
}
@Test
public void unsatCoreWithAssumptionsTest() throws SolverException, InterruptedException {
assume()
.withMessage(
"Solver %s does not support unsat core generation over assumptions", solverToUse())
.that(solverToUse())
.isNoneOf(PRINCESS, BOOLECTOR, CVC4, CVC5);
try (ProverEnvironment pe =
context.newProverEnvironment(GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS)) {
pe.push();
pe.addConstraint(imgr.equal(imgr.makeVariable("y"), imgr.makeNumber(2)));
BooleanFormula selector = bmgr.makeVariable("b");
pe.addConstraint(bmgr.or(selector, imgr.equal(imgr.makeVariable("y"), imgr.makeNumber(1))));
Optional<List<BooleanFormula>> res =
pe.unsatCoreOverAssumptions(ImmutableList.of(bmgr.not(selector)));
assertThat(res).isPresent();
List<BooleanFormula> unsatCore = res.orElseThrow();
assertThat(unsatCore).containsExactly(bmgr.not(selector));
}
}
}
| 6,321 | 39.525641 | 105 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/QuantifierManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.StringType;
import com.google.common.collect.ImmutableList;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.Tactic;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
@SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "test code")
public class QuantifierManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private IntegerFormula x;
private ArrayFormula<IntegerFormula, IntegerFormula> a;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula a_at_x_eq_1;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula a_at_x_eq_0;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula forall_x_a_at_x_eq_0;
private static final int bvWidth = 16;
private BitvectorFormula xbv;
private ArrayFormula<BitvectorFormula, BitvectorFormula> bvArray;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula bvArray_at_x_eq_1;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula bvArray_at_x_eq_0;
@SuppressWarnings("checkstyle:membername")
private BooleanFormula bv_forall_x_a_at_x_eq_0;
@Before
public void setUpLIA() {
requireIntegers();
requireArrays();
requireQuantifiers();
x = imgr.makeVariable("x");
a = amgr.makeArray("a", FormulaType.IntegerType, FormulaType.IntegerType);
a_at_x_eq_1 = imgr.equal(amgr.select(a, x), imgr.makeNumber(1));
a_at_x_eq_0 = imgr.equal(amgr.select(a, x), imgr.makeNumber(0));
forall_x_a_at_x_eq_0 = qmgr.forall(ImmutableList.of(x), a_at_x_eq_0);
}
@Before
public void setUpBV() {
requireBitvectors();
requireArrays();
requireQuantifiers();
assume()
.withMessage("Solver %s does not support quantifiers via JavaSMT", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
xbv = bvmgr.makeVariable(bvWidth, "xbv");
bvArray =
amgr.makeArray(
"bvArray",
FormulaType.getBitvectorTypeWithSize(bvWidth),
FormulaType.getBitvectorTypeWithSize(bvWidth));
bvArray_at_x_eq_1 = bvmgr.equal(amgr.select(bvArray, xbv), bvmgr.makeBitvector(bvWidth, 1));
bvArray_at_x_eq_0 = bvmgr.equal(amgr.select(bvArray, xbv), bvmgr.makeBitvector(bvWidth, 0));
bv_forall_x_a_at_x_eq_0 = qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0);
}
private SolverException handleSolverException(SolverException e) throws SolverException {
// The tests in this class use quantifiers and thus solver failures are expected.
// We do not ignore all SolverExceptions in order to not hide bugs,
// but only for Princess and CVC4 which are known to not be able to solve all tests here.
if (solverToUse() == Solvers.PRINCESS || solverToUse() == Solvers.CVC4) {
assume().withMessage(e.getMessage()).fail();
}
throw e;
}
private static final UniqueIdGenerator index = new UniqueIdGenerator(); // to get different names
@Test
public void testLIAForallArrayConjunctUnsat() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) AND (b[123] = 1) is UNSAT
requireIntegers();
BooleanFormula f =
bmgr.and(
qmgr.forall(ImmutableList.of(x), a_at_x_eq_0),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testBVForallArrayConjunctUnsat() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) AND (b[123] = 1) is UNSAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.and(
qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0),
bvmgr.equal(
amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)),
bvmgr.makeBitvector(bvWidth, 1)));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testLIAForallArrayConjunctSat() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) AND (b[123] = 0) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(
qmgr.forall(ImmutableList.of(x), a_at_x_eq_0),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0)));
try {
// CVC4 and Princess fail this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testBVForallArrayConjunctSat() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) AND (b[123] = 0) is SAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.and(
qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0),
bvmgr.equal(
amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)),
bvmgr.makeBitvector(bvWidth, 0)));
try {
// CVC4 and Princess fail this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIAForallArrayDisjunct1() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) AND (b[123] = 1 OR b[123] = 0) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(
qmgr.forall(ImmutableList.of(x), a_at_x_eq_0),
bmgr.or(
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0))));
try {
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIAForallArrayDisjunctSat2() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (forall x . b[x] = 0) OR (b[123] = 1) is SAT
requireIntegers();
BooleanFormula f =
bmgr.or(
qmgr.forall(ImmutableList.of(x), a_at_x_eq_0),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)));
try {
// CVC4 fails this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIANotExistsArrayConjunct1() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (not exists x . not b[x] = 0) AND (b[123] = 1) is UNSAT
requireIntegers();
BooleanFormula f =
bmgr.and(
bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)));
try {
assertThatFormula(f).isUnsatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIANotExistsArrayConjunct2() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (not exists x . not b[x] = 0) AND (b[123] = 0) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(
bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0)));
try {
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIANotExistsArrayConjunct3() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (not exists x . b[x] = 0) AND (b[123] = 0) is UNSAT
requireIntegers();
BooleanFormula f =
bmgr.and(
bmgr.not(qmgr.exists(ImmutableList.of(x), a_at_x_eq_0)),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0)));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testLIANotExistsArrayDisjunct1() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (not exists x . not b[x] = 0) AND (b[123] = 1 OR b[123] = 0) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(
bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))),
bmgr.or(
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0))));
try {
// CVC4 and Princess fail this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIANotExistsArrayDisjunct2() throws SolverException, InterruptedException {
// (not exists x . not b[x] = 0) OR (b[123] = 1) is SAT
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
requireIntegers();
BooleanFormula f =
bmgr.or(
bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)));
try {
// CVC4 fails this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIAExistsArrayConjunct1() throws SolverException, InterruptedException {
// (exists x . b[x] = 0) AND (b[123] = 1) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(
qmgr.exists(ImmutableList.of(x), a_at_x_eq_0),
imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVExistsArrayConjunct1() throws SolverException, InterruptedException {
// (exists x . b[x] = 0) AND (b[123] = 1) is SAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.and(
qmgr.exists(ImmutableList.of(x), a_at_x_eq_0),
bvmgr.equal(
amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)),
bvmgr.makeBitvector(bvWidth, 1)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testLIAExistsArrayConjunct2() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (exists x . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT
requireIntegers();
BooleanFormula f =
bmgr.and(qmgr.exists(ImmutableList.of(x), a_at_x_eq_1), forall_x_a_at_x_eq_0);
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testBVExistsArrayConjunct2() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (exists x . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.and(qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1), bv_forall_x_a_at_x_eq_0);
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testLIAExistsArrayConjunct3() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// (exists x . b[x] = 0) AND (forall x . b[x] = 0) is SAT
requireIntegers();
BooleanFormula f =
bmgr.and(qmgr.exists(ImmutableList.of(x), a_at_x_eq_0), forall_x_a_at_x_eq_0);
try {
// CVC4 and Princess fail this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testBVExistsArrayConjunct3() throws SolverException, InterruptedException {
// (exists x . b[x] = 0) AND (forall x . b[x] = 0) is SAT
requireBitvectors();
// Princess does not support bitvectors in arrays
// Boolector quants need to be reworked
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC5, Solvers.CVC4, Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.and(qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_0), bv_forall_x_a_at_x_eq_0);
try {
// CVC4 and Princess fail this
assertThatFormula(f).isSatisfiable();
} catch (SolverException e) {
throw handleSolverException(e);
}
}
@Test
public void testLIAExistsArrayDisjunct1() throws SolverException, InterruptedException {
// (exists x . b[x] = 0) OR (forall x . b[x] = 1) is SAT
requireIntegers();
BooleanFormula f =
bmgr.or(
qmgr.exists(ImmutableList.of(x), a_at_x_eq_0),
qmgr.forall(ImmutableList.of(x), a_at_x_eq_1));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVExistsArrayDisjunct1() throws SolverException, InterruptedException {
// (exists x . b[x] = 0) OR (forall x . b[x] = 1) is SAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.or(
qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_0),
qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_1));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testLIAExistsArrayDisjunct2() throws SolverException, InterruptedException {
// (exists x . b[x] = 1) OR (exists x . b[x] = 1) is SAT
requireIntegers();
BooleanFormula f =
bmgr.or(
qmgr.exists(ImmutableList.of(x), a_at_x_eq_1),
qmgr.exists(ImmutableList.of(x), a_at_x_eq_1));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVExistsArrayDisjunct2() throws SolverException, InterruptedException {
// (exists x . b[x] = 1) OR (exists x . b[x] = 1) is SAT
requireBitvectors();
// Princess does not support bitvectors in arrays
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula f =
bmgr.or(
qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1),
qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testLIAContradiction() throws SolverException, InterruptedException {
// forall x . x = x+1 is UNSAT
requireIntegers();
BooleanFormula f =
qmgr.forall(ImmutableList.of(x), imgr.equal(x, imgr.add(x, imgr.makeNumber(1))));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testBVContradiction() throws SolverException, InterruptedException {
// forall x . x = x+1 is UNSAT
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
int width = 16;
BitvectorFormula z = bvmgr.makeVariable(width, "z");
BooleanFormula f =
qmgr.forall(
ImmutableList.of(z), bvmgr.equal(z, bvmgr.add(z, bvmgr.makeBitvector(width, 1))));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testLIASimple() throws SolverException, InterruptedException {
// forall x . x+2 = x+1+1 is SAT
requireIntegers();
BooleanFormula f =
qmgr.forall(
ImmutableList.of(x),
imgr.equal(
imgr.add(x, imgr.makeNumber(2)),
imgr.add(imgr.add(x, imgr.makeNumber(1)), imgr.makeNumber(1))));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVSimple() throws SolverException, InterruptedException {
// forall z . z+2 = z+1+1 is SAT
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
int width = 16;
BitvectorFormula z = bvmgr.makeVariable(width, "z");
BooleanFormula f =
qmgr.forall(
ImmutableList.of(z),
bvmgr.equal(
bvmgr.add(z, bvmgr.makeBitvector(width, 2)),
bvmgr.add(
bvmgr.add(z, bvmgr.makeBitvector(width, 1)), bvmgr.makeBitvector(width, 1))));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testLIAEquality() throws SolverException, InterruptedException {
requireIntegers();
// Note that due to the variable cache we simply get the existing var x here!
IntegerFormula z = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
BooleanFormula f =
qmgr.forall(ImmutableList.of(z), qmgr.exists(ImmutableList.of(y), imgr.equal(z, y)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVEquality() throws SolverException, InterruptedException {
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z");
BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y");
BooleanFormula f =
qmgr.forall(ImmutableList.of(z), qmgr.exists(ImmutableList.of(y), bvmgr.equal(z, y)));
assertThatFormula(f).isSatisfiable();
}
@Test
public void testBVEquality2() throws SolverException, InterruptedException {
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z");
BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y");
BooleanFormula f = qmgr.forall(ImmutableList.of(z, y), bvmgr.equal(z, y));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testBVEquality3() throws SolverException, InterruptedException {
// exists z . (forall y . z = y && z + 2 > z)
// UNSAT because of bv behaviour
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z");
BitvectorFormula zPlusTwo =
bvmgr.add(bvmgr.makeVariable(bvWidth, "z"), bvmgr.makeBitvector(bvWidth, 2));
BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y");
BooleanFormula f =
qmgr.exists(
ImmutableList.of(z),
qmgr.forall(
ImmutableList.of(y),
bmgr.and(bvmgr.equal(z, y), bvmgr.greaterThan(zPlusTwo, z, false))));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testLIABoundVariables() throws SolverException, InterruptedException {
// If the free and bound vars are equal, this will be UNSAT
requireIntegers();
IntegerFormula aa = imgr.makeVariable("aa");
IntegerFormula one = imgr.makeNumber(1);
BooleanFormula restrict = bmgr.not(imgr.equal(aa, one));
// x != 1 && exists x . (x == 1)
BooleanFormula f = qmgr.exists(ImmutableList.of(aa), imgr.equal(aa, one));
assertThatFormula(bmgr.and(f, restrict)).isSatisfiable();
}
@Test
public void testBVBoundVariables() throws SolverException, InterruptedException {
// If the free and bound vars are equal, this will be UNSAT
requireBitvectors();
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
int width = 2;
BitvectorFormula aa = bvmgr.makeVariable(width, "aa");
BitvectorFormula one = bvmgr.makeBitvector(width, 1);
BooleanFormula restrict = bmgr.not(bvmgr.equal(aa, one));
// x != 1 && exists x . (x == 1)
BooleanFormula f = qmgr.exists(ImmutableList.of(aa), bvmgr.equal(aa, one));
assertThatFormula(bmgr.and(f, restrict)).isSatisfiable();
}
@Test
public void testQELight() throws InterruptedException {
requireIntegers();
assume().that(solverToUse()).isEqualTo(Solvers.Z3);
// exists y : (y=4 && x=y+3) --> simplified: x=7
IntegerFormula y = imgr.makeVariable("y");
BooleanFormula f1 =
qmgr.exists(
y,
bmgr.and(
imgr.equal(y, imgr.makeNumber(4)), imgr.equal(x, imgr.add(y, imgr.makeNumber(3)))));
BooleanFormula out = mgr.applyTactic(f1, Tactic.QE_LIGHT);
assertThat(out).isEqualTo(imgr.equal(x, imgr.makeNumber(7)));
}
@Test
public void testIntrospectionForall() {
requireIntegers();
BooleanFormula forall = qmgr.forall(ImmutableList.of(x), a_at_x_eq_0);
final AtomicBoolean isQuantifier = new AtomicBoolean(false);
final AtomicBoolean isForall = new AtomicBoolean(false);
final AtomicInteger numBound = new AtomicInteger(0);
// Test introspection with visitors.
mgr.visit(
forall,
new DefaultFormulaVisitor<Void>() {
@Override
protected Void visitDefault(Formula f) {
return null;
}
@Override
public Void visitQuantifier(
BooleanFormula f,
Quantifier quantifier,
List<Formula> boundVariables,
BooleanFormula body) {
isForall.set(quantifier == Quantifier.FORALL);
isQuantifier.set(true);
numBound.set(boundVariables.size());
return null;
}
});
}
@Test
public void testIntrospectionExists() {
requireIntegers();
BooleanFormula exists = qmgr.exists(ImmutableList.of(x), a_at_x_eq_0);
final AtomicBoolean isQuantifier = new AtomicBoolean(false);
final AtomicBoolean isForall = new AtomicBoolean(false);
final List<Formula> boundVars = new ArrayList<>();
// Test introspection with visitors.
mgr.visit(
exists,
new DefaultFormulaVisitor<Void>() {
@Override
protected Void visitDefault(Formula f) {
return null;
}
@Override
public Void visitQuantifier(
BooleanFormula f,
Quantifier quantifier,
List<Formula> boundVariables,
BooleanFormula body) {
assertThat(isQuantifier.get()).isFalse();
isForall.set(quantifier == Quantifier.FORALL);
isQuantifier.set(true);
boundVars.addAll(boundVariables);
return null;
}
});
assertThat(isQuantifier.get()).isTrue();
assertThat(isForall.get()).isFalse();
assume()
.withMessage("Quantifier introspection in JavaSMT for Princess is currently not complete.")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
assertThat(boundVars).hasSize(1);
}
@Test(expected = IllegalArgumentException.class)
public void testEmpty() {
assume()
.withMessage("TODO: The JavaSMT code for Princess explicitly allows this.")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
// An empty list of quantified variables throws an exception.
@SuppressWarnings("unused")
BooleanFormula quantified = qmgr.exists(ImmutableList.of(), bmgr.makeVariable("b"));
}
@Test
public void checkLIAQuantifierElimination() throws InterruptedException, SolverException {
// build formula: (forall x . ((x < 5) | (7 < x + y)))
// quantifier-free equivalent: (2 < y)
requireIntegers();
IntegerFormula xx = imgr.makeVariable("x");
IntegerFormula yy = imgr.makeVariable("y");
BooleanFormula f =
qmgr.forall(
xx,
bmgr.or(
imgr.lessThan(xx, imgr.makeNumber(5)),
imgr.lessThan(imgr.makeNumber(7), imgr.add(xx, yy))));
BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f);
assertThatFormula(qFreeF).isEquivalentTo(imgr.lessThan(imgr.makeNumber(2), yy));
}
@Test
public void checkLIAQuantifierEliminationFail() throws InterruptedException, SolverException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// build formula: (exists x : arr[x] = 3) && (forall y: arr[y] = 2)
// as there is no quantifier free equivalent, it should return the input formula.
requireIntegers();
IntegerFormula xx = imgr.makeVariable("x");
IntegerFormula yy = imgr.makeVariable("y");
ArrayFormula<IntegerFormula, IntegerFormula> a1 =
amgr.makeArray("a1", FormulaType.IntegerType, FormulaType.IntegerType);
BooleanFormula f =
bmgr.and(
qmgr.exists(xx, imgr.equal(amgr.select(a1, xx), imgr.makeNumber(3))),
qmgr.forall(yy, imgr.equal(amgr.select(a1, yy), imgr.makeNumber(2))));
BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f);
assertThatFormula(qFreeF).isEquivalentTo(f);
}
@Test
public void checkBVQuantifierEliminationFail() throws InterruptedException, SolverException {
// build formula: (exists x : arr[x] = 3) && (forall y: arr[y] = 2)
// as there is no quantifier free equivalent, it should return the input formula.
requireBitvectors();
// Boolector quants need to be reworked
// Princess does not support bitvectors in arrays
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC5, Solvers.BOOLECTOR, Solvers.PRINCESS);
int width = 2;
BitvectorFormula xx = bvmgr.makeVariable(width, "x_bv");
BitvectorFormula yy = bvmgr.makeVariable(width, "y_bv");
ArrayFormula<BitvectorFormula, BitvectorFormula> array =
amgr.makeArray(
"array",
FormulaType.getBitvectorTypeWithSize(width),
FormulaType.getBitvectorTypeWithSize(width));
BooleanFormula f =
bmgr.and(
qmgr.exists(xx, bvmgr.equal(amgr.select(array, xx), bvmgr.makeBitvector(width, 3))),
qmgr.forall(yy, bvmgr.equal(amgr.select(array, yy), bvmgr.makeBitvector(width, 2))));
BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f);
assertThatFormula(qFreeF).isEquivalentTo(f);
}
@Test
public void checkBVQuantifierElimination() throws InterruptedException, SolverException {
requireBitvectors();
// build formula: exists y : bv[2]. x * y = 1
// quantifier-free equivalent: x = 1 | x = 3
// or extract_0_0 x = 1
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
int i = index.getFreshId();
int width = 2;
BitvectorFormula xx = bvmgr.makeVariable(width, "x" + i);
BitvectorFormula yy = bvmgr.makeVariable(width, "y" + i);
BooleanFormula f =
qmgr.exists(yy, bvmgr.equal(bvmgr.multiply(xx, yy), bvmgr.makeBitvector(width, 1)));
BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f);
assertThatFormula(qFreeF)
.isEquivalentTo(bvmgr.equal(bvmgr.extract(xx, 0, 0), bvmgr.makeBitvector(1, 1)));
}
/** Quant elim test based on a crash in Z3. */
@Test
public void checkBVQuantifierElimination2() throws InterruptedException, SolverException {
requireBitvectors();
// build formula: exists a2 : (and (= a2 #x00000006)
// (= b2 #x00000006)
// (= a3 #x00000000))
// quantifier-free equivalent: (and (= b2 #x00000006)
// (= a3 #x00000000))
// Boolector quants need to be reworked
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
// Z3 fails this currently. Remove once thats not longer the case!
assume().that(solverToUse()).isNotEqualTo(Solvers.Z3);
int width = 32;
BitvectorFormula a2 = bvmgr.makeVariable(width, "a2");
BitvectorFormula b2 = bvmgr.makeVariable(width, "b2");
BitvectorFormula a3 = bvmgr.makeVariable(width, "a3");
BooleanFormula fAnd =
bmgr.and(
bvmgr.equal(a2, bvmgr.makeBitvector(width, 6)),
bvmgr.equal(b2, bvmgr.makeBitvector(width, 6)),
bvmgr.equal(a3, bvmgr.makeBitvector(width, 0)));
BooleanFormula f = qmgr.exists(a2, fAnd);
BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f);
assertThatFormula(qFreeF)
.isEquivalentTo(
bmgr.and(
bvmgr.equal(b2, bvmgr.makeBitvector(width, 6)),
bvmgr.equal(a3, bvmgr.makeBitvector(width, 0))));
}
@Test
public void testExistsRestrictedRange() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
ArrayFormula<IntegerFormula, IntegerFormula> b =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1));
BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0));
BooleanFormula exists10to20bx1 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1);
BooleanFormula forallXbx0 = qmgr.forall(x, bAtXEq0);
// (exists x in [10..20] . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT
assertThatFormula(bmgr.and(exists10to20bx1, forallXbx0)).isUnsatisfiable();
// (exists x in [10..20] . b[x] = 1) AND (b[10] = 0) is SAT
assertThatFormula(
bmgr.and(
exists10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(10)), imgr.makeNumber(0))))
.isSatisfiable();
// (exists x in [10..20] . b[x] = 1) AND (b[1000] = 0) is SAT
assertThatFormula(
bmgr.and(
exists10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(1000)), imgr.makeNumber(0))))
.isSatisfiable();
}
@Test
public void testExistsRestrictedRangeWithoutInconclusiveSolvers()
throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5, Solvers.PRINCESS);
ArrayFormula<IntegerFormula, IntegerFormula> b =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1));
BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0));
BooleanFormula exists10to20bx0 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq0);
BooleanFormula exists10to20bx1 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1);
BooleanFormula forallXbx1 = qmgr.forall(x, bAtXEq1);
BooleanFormula forallXbx0 = qmgr.forall(x, bAtXEq0);
// (exists x in [10..20] . b[x] = 0) AND (forall x . b[x] = 0) is SAT
assertThatFormula(bmgr.and(exists10to20bx0, forallXbx0)).isSatisfiable();
// (exists x in [10..20] . b[x] = 1) AND (forall x . b[x] = 1) is SAT
assertThatFormula(bmgr.and(exists10to20bx1, forallXbx1)).isSatisfiable();
}
@Test
public void testForallRestrictedRange() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
ArrayFormula<IntegerFormula, IntegerFormula> b =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1));
BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0));
BooleanFormula forall10to20bx1 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1);
// (forall x in [10..20] . b[x] = 1) AND (exits x in [15..17] . b[x] = 0) is UNSAT
assertThatFormula(
bmgr.and(forall10to20bx1, exists(x, imgr.makeNumber(15), imgr.makeNumber(17), bAtXEq0)))
.isUnsatisfiable();
// (forall x in [10..20] . b[x] = 1) AND b[10] = 0 is UNSAT
assertThatFormula(
bmgr.and(
forall10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(10)), imgr.makeNumber(0))))
.isUnsatisfiable();
// (forall x in [10..20] . b[x] = 1) AND b[20] = 0 is UNSAT
assertThatFormula(
bmgr.and(
forall10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(20)), imgr.makeNumber(0))))
.isUnsatisfiable();
}
@Test
public void testForallRestrictedRangeWithoutConclusiveSolvers()
throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.CVC5, Solvers.PRINCESS);
ArrayFormula<IntegerFormula, IntegerFormula> b =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1));
BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0));
BooleanFormula forall10to20bx0 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq0);
BooleanFormula forall10to20bx1 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1);
// (forall x in [10..20] . b[x] = 0) AND (forall x . b[x] = 0) is SAT
assertThatFormula(bmgr.and(forall10to20bx0, qmgr.forall(x, bAtXEq0))).isSatisfiable();
// (forall x in [10..20] . b[x] = 1) AND b[9] = 0 is SAT
assertThatFormula(
bmgr.and(
forall10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(9)), imgr.makeNumber(0))))
.isSatisfiable();
// (forall x in [10..20] . b[x] = 1) AND b[21] = 0 is SAT
assertThatFormula(
bmgr.and(
forall10to20bx1,
imgr.equal(amgr.select(b, imgr.makeNumber(21)), imgr.makeNumber(0))))
.isSatisfiable();
// (forall x in [10..20] . b[x] = 1) AND (forall x in [0..20] . b[x] = 0) is UNSAT
assertThatFormula(
bmgr.and(forall10to20bx1, forall(x, imgr.makeNumber(0), imgr.makeNumber(20), bAtXEq0)))
.isUnsatisfiable();
// (forall x in [10..20] . b[x] = 1) AND (forall x in [0..9] . b[x] = 0) is SAT
assertThatFormula(
bmgr.and(forall10to20bx1, forall(x, imgr.makeNumber(0), imgr.makeNumber(9), bAtXEq0)))
.isSatisfiable();
}
@Test
public void testExistsBasicStringTheorie() throws SolverException, InterruptedException {
requireStrings();
requireIntegers();
// exists var ("a" < var < "c") & length var == 1 -> var == "b"
StringFormula stringA = smgr.makeString("a");
StringFormula stringC = smgr.makeString("c");
StringFormula var = smgr.makeVariable("var");
BooleanFormula query =
qmgr.exists(
var,
bmgr.and(
imgr.equal(smgr.length(var), imgr.makeNumber(1)),
smgr.lessThan(stringA, var),
smgr.lessThan(var, stringC)));
assertThatFormula(query).isSatisfiable();
}
@Test
public void testForallBasicStringTheorie() throws SolverException, InterruptedException {
requireStrings();
requireIntegers();
// forall var ("a" < var < "c") & length var == 1
StringFormula stringA = smgr.makeString("a");
StringFormula stringC = smgr.makeString("c");
StringFormula var = smgr.makeVariable("var");
BooleanFormula query =
qmgr.forall(
var,
bmgr.and(
imgr.equal(smgr.length(var), imgr.makeNumber(1)),
smgr.lessThan(stringA, var),
smgr.lessThan(var, stringC)));
assertThatFormula(query).isUnsatisfiable();
}
@Test
public void testExistsBasicStringArray() throws SolverException, InterruptedException {
requireStrings();
requireIntegers();
// exists var (var = select(store(arr, 2, "bla"), 2)
IntegerFormula two = imgr.makeNumber(2);
StringFormula string = smgr.makeString("bla");
StringFormula var = smgr.makeVariable("var");
ArrayFormula<IntegerFormula, StringFormula> arr =
amgr.makeArray("arr", FormulaType.IntegerType, StringType);
BooleanFormula query =
qmgr.exists(var, smgr.equal(var, amgr.select(amgr.store(arr, two, string), two)));
assertThatFormula(query).isSatisfiable();
}
@Test
public void testForallBasicStringArray() throws SolverException, InterruptedException {
requireStrings();
requireIntegers();
// forall var (var = select(store(arr, 2, "bla"), 2)
IntegerFormula two = imgr.makeNumber(2);
StringFormula string = smgr.makeString("bla");
StringFormula var = smgr.makeVariable("var");
ArrayFormula<IntegerFormula, StringFormula> arr =
amgr.makeArray("arr", FormulaType.IntegerType, StringType);
BooleanFormula query =
qmgr.forall(var, smgr.equal(var, amgr.select(amgr.store(arr, two, string), two)));
assertThatFormula(query).isUnsatisfiable();
}
private BooleanFormula forall(
final IntegerFormula pVariable,
final IntegerFormula pLowerBound,
final IntegerFormula pUpperBound,
final BooleanFormula pBody) {
return qmgr.forall(
pVariable,
bmgr.implication(
bmgr.and(
imgr.greaterOrEquals(pVariable, pLowerBound),
imgr.lessOrEquals(pVariable, pUpperBound)),
pBody));
}
private BooleanFormula exists(
final IntegerFormula pVariable,
final IntegerFormula pLowerBound,
final IntegerFormula pUpperBound,
final BooleanFormula pBody) {
List<BooleanFormula> constraintsAndBody =
ImmutableList.of(
imgr.greaterOrEquals(pVariable, pLowerBound),
imgr.lessOrEquals(pVariable, pUpperBound),
pBody);
return qmgr.exists(pVariable, bmgr.and(constraintsAndBody));
}
}
| 41,980 | 36.651121 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/RationalFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import com.google.common.collect.Iterables;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
public class RationalFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private static final double[] SOME_DOUBLES =
new double[] {
0, 0.1, 0.25, 0.5, 1, 1.5, 1.9, 2.1, 2.5, -0.1, -0.5, -1, -1.5, -1.9, -2.1, -2.5,
};
@Test
public void rationalToIntTest() throws SolverException, InterruptedException {
requireRationals();
for (double v : SOME_DOUBLES) {
IntegerFormula i = imgr.makeNumber((int) Math.floor(v));
RationalFormula r = rmgr.makeNumber(v);
assertThat(mgr.getFormulaType(i)).isEqualTo(FormulaType.IntegerType);
assertThat(mgr.getFormulaType(rmgr.floor(r))).isEqualTo(FormulaType.IntegerType);
assertThatFormula(imgr.equal(i, rmgr.floor(r))).isSatisfiable();
}
}
@Test
public void intToIntTest() throws SolverException, InterruptedException {
requireIntegers();
for (double v : SOME_DOUBLES) {
IntegerFormula i = imgr.makeNumber((int) Math.floor(v));
assertThat(mgr.getFormulaType(i)).isEqualTo(FormulaType.IntegerType);
assertThat(mgr.getFormulaType(imgr.floor(i))).isEqualTo(FormulaType.IntegerType);
assertThatFormula(imgr.equal(i, imgr.floor(i))).isTautological();
}
}
@Test
public void intToIntWithRmgrTest() throws SolverException, InterruptedException {
requireRationals();
for (double v : SOME_DOUBLES) {
IntegerFormula i = imgr.makeNumber((int) Math.floor(v));
assertThat(mgr.getFormulaType(i)).isEqualTo(FormulaType.IntegerType);
assertThat(mgr.getFormulaType(imgr.floor(i))).isEqualTo(FormulaType.IntegerType);
assertThatFormula(imgr.equal(i, rmgr.floor(i))).isTautological();
}
}
@Test
public void floorIsLessOrEqualsValueTest() throws SolverException, InterruptedException {
requireRationals();
requireQuantifiers();
RationalFormula v = rmgr.makeVariable("v");
assertThatFormula(rmgr.lessOrEquals(rmgr.floor(v), v)).isTautological();
}
@Test
public void floorIsGreaterThanValueTest() throws SolverException, InterruptedException {
requireRationals();
requireQuantifiers();
RationalFormula v = rmgr.makeVariable("v");
assertThatFormula(rmgr.lessOrEquals(rmgr.floor(v), v)).isTautological();
}
@Test
public void forallFloorIsLessOrEqualsValueTest() throws SolverException, InterruptedException {
requireRationals();
requireQuantifiers();
RationalFormula v = rmgr.makeVariable("v");
assertThatFormula(qmgr.forall(v, rmgr.lessOrEquals(rmgr.floor(v), v))).isTautological();
}
@Test
public void forallFloorIsLessThanValueTest() throws SolverException, InterruptedException {
requireRationals();
requireQuantifiers();
RationalFormula v = rmgr.makeVariable("v");
// counterexample: all integers
assertThatFormula(qmgr.forall(v, rmgr.lessThan(rmgr.floor(v), v))).isUnsatisfiable();
}
@Test
public void visitFloorTest() {
requireRationals();
IntegerFormula f = rmgr.floor(rmgr.makeVariable("v"));
assertThat(mgr.extractVariables(f)).hasSize(1);
FunctionCollector collector = new FunctionCollector();
assertThat(mgr.visit(f, collector)).isTrue();
assertThat(Iterables.getOnlyElement(collector.functions).getKind())
.isEqualTo(FunctionDeclarationKind.FLOOR);
}
private static final class FunctionCollector extends DefaultFormulaVisitor<Boolean> {
private final Set<FunctionDeclaration<?>> functions = new HashSet<>();
@Override
public Boolean visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
functions.add(pFunctionDeclaration);
return true;
}
@Override
protected Boolean visitDefault(Formula pF) {
return true;
}
}
@SuppressWarnings("CheckReturnValue")
@Test(expected = Exception.class)
public void failOnInvalidString() {
rmgr.makeNumber("a");
assert_().fail();
}
}
| 4,891 | 34.708029 | 97 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverAllSatTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BasicProverEnvironment.AllSatCallback;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
@RunWith(Parameterized.class)
public class SolverAllSatTest extends SolverBasedTest0 {
@Parameters(name = "solver {0} with prover {1}")
public static Iterable<Object[]> getAllSolvers() {
List<Object[]> junitParams = new ArrayList<>();
for (Solvers solver : Solvers.values()) {
junitParams.add(new Object[] {solver, "normal"});
junitParams.add(new Object[] {solver, "itp"});
junitParams.add(new Object[] {solver, "opt"});
}
return junitParams;
}
@Parameter(0)
public Solvers solver;
@Parameter(1)
public String proverEnv;
@Override
protected Solvers solverToUse() {
return solver;
}
private BasicProverEnvironment<?> env;
@Before
public void setupEnvironment() {
switch (proverEnv) {
case "normal":
env = context.newProverEnvironment(ProverOptions.GENERATE_ALL_SAT);
break;
case "itp":
requireInterpolation();
// TODO how can we support allsat in MathSat5-interpolation-prover?
assume().that(solverToUse()).isNotEqualTo(Solvers.MATHSAT5);
// CVC4 and Boolector do not support interpolation
assume().that(solverToUse()).isNoneOf(Solvers.CVC4, Solvers.BOOLECTOR, Solvers.Z3);
env = context.newProverEnvironmentWithInterpolation(ProverOptions.GENERATE_ALL_SAT);
break;
case "opt":
requireOptimization();
env = context.newOptimizationProverEnvironment(ProverOptions.GENERATE_ALL_SAT);
break;
default:
throw new AssertionError("unexpected");
}
}
@After
public void closeEnvironment() {
if (env != null) {
env.close();
}
}
private static final String EXPECTED_RESULT = "AllSatTest_unsat";
private static class TestAllSatCallback implements AllSatCallback<String> {
private final List<List<BooleanFormula>> models = new ArrayList<>();
@Override
public void apply(List<BooleanFormula> pModel) {
models.add(ImmutableList.copyOf(pModel));
}
@Override
public String getResult() {
return EXPECTED_RESULT;
}
}
@Test
public void allSatTest_unsat() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("i");
IntegerFormula n1 = imgr.makeNumber(1);
IntegerFormula n2 = imgr.makeNumber(2);
BooleanFormula cond1 = imgr.equal(a, n1);
BooleanFormula cond2 = imgr.equal(a, n2);
BooleanFormula v1 = bmgr.makeVariable("b1");
BooleanFormula v2 = bmgr.makeVariable("b2");
env.push(cond1);
env.push(cond2);
env.push(bmgr.equivalence(v1, cond1));
env.push(bmgr.equivalence(v2, cond2));
TestAllSatCallback callback =
new TestAllSatCallback() {
@Override
public void apply(List<BooleanFormula> pModel) {
assert_()
.withMessage("Formula is unsat, but all-sat callback called with model " + pModel)
.fail();
}
};
assertThat(env.allSat(callback, ImmutableList.of(v1, v2))).isEqualTo(EXPECTED_RESULT);
}
@Test
public void allSatTest_xor() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("i");
IntegerFormula n1 = imgr.makeNumber(1);
IntegerFormula n2 = imgr.makeNumber(2);
BooleanFormula cond1 = imgr.equal(a, n1);
BooleanFormula cond2 = imgr.equal(a, n2);
BooleanFormula v1 = bmgr.makeVariable("b1");
BooleanFormula v2 = bmgr.makeVariable("b2");
env.push(bmgr.xor(cond1, cond2));
env.push(bmgr.equivalence(v1, cond1));
env.push(bmgr.equivalence(v2, cond2));
// ((i=1) XOR (i=2)) & b1 <=> (i=1) & b2 <=> (i=2)
// query ALLSAT for predicates [b1, b2] --> {[b1,-b2], [-b1,b2]}
TestAllSatCallback callback = new TestAllSatCallback();
assertThat(env.allSat(callback, ImmutableList.of(v1, v2))).isEqualTo(EXPECTED_RESULT);
assertThat(callback.models)
.containsExactly(ImmutableList.of(v1, bmgr.not(v2)), ImmutableList.of(bmgr.not(v1), v2));
}
@Test
public void allSatTest_nondetValue() throws SolverException, InterruptedException {
BooleanFormula v1 = bmgr.makeVariable("b1");
BooleanFormula v2 = bmgr.makeVariable("b2");
env.push(v1);
TestAllSatCallback callback = new TestAllSatCallback();
assertThat(env.allSat(callback, ImmutableList.of(v1, v2))).isEqualTo(EXPECTED_RESULT);
assertThat(callback.models)
.isAnyOf(
ImmutableList.of(ImmutableList.of(v1)),
ImmutableList.of(ImmutableList.of(v1, v2), ImmutableList.of(v1, bmgr.not(v2))),
ImmutableList.of(ImmutableList.of(v1, bmgr.not(v2)), ImmutableList.of(v1, v2)));
}
@Test
public void allSatTest_withQuantifier() throws SolverException, InterruptedException {
requireBitvectors();
requireQuantifiers();
assume()
.withMessage("solver does only partially support quantifiers")
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
if ("opt".equals(proverEnv)) {
assume()
.withMessage("solver reports a partial model when using optimization")
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
}
if ("itp".equals(proverEnv)) {
assume()
.withMessage("solver reports a inconclusive sat-check when using interpolation")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
}
// (y = 1)
// & (PRED1 <-> (y = 1))
// & (PRED3 <-> ALL x_0. (3 * x_0 != y))
// query ALLSAT for predicates [PRED1, PRED3] --> {[PRED1, -PRED3]}
// ugly detail in bitvector theory: 2863311531*3=1 mod 2^32,
// thus the quantified part from above is FALSE.
int bitsize = 32;
BitvectorFormula y = bvmgr.makeVariable(bitsize, "y");
BitvectorFormula one = bvmgr.makeBitvector(bitsize, 1);
BitvectorFormula three = bvmgr.makeBitvector(bitsize, 3);
BitvectorFormula bound = bvmgr.makeVariable(bitsize, "x_0");
BooleanFormula pred1 = bmgr.makeVariable("pred1");
BooleanFormula pred3 = bmgr.makeVariable("pred3");
BooleanFormula query =
bmgr.and(
bvmgr.equal(y, one),
bmgr.equivalence(pred1, bvmgr.equal(y, one)),
bmgr.equivalence(
pred3,
qmgr.forall(
ImmutableList.of(bound),
bmgr.not(bvmgr.equal(y, bvmgr.multiply(three, bound))))));
env.push(query);
assertThat(env.isUnsat()).isFalse();
TestAllSatCallback callback = new TestAllSatCallback();
assertThat(env.allSat(callback, ImmutableList.of(pred1, pred3))).isEqualTo(EXPECTED_RESULT);
assertThat(callback.models)
.isEqualTo(ImmutableList.of(ImmutableList.of(pred1, bmgr.not(pred3))));
}
}
| 8,030 | 30.494118 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverBasedTest0.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.test.BooleanFormulaSubject.assertUsing;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.truth.Truth;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Collection;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.ShutdownManager;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.java_smt.SolverContextFactory;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormulaManager;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BitvectorFormulaManager;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.EnumerationFormulaManager;
import org.sosy_lab.java_smt.api.FloatingPointFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager;
import org.sosy_lab.java_smt.api.RationalFormulaManager;
import org.sosy_lab.java_smt.api.SolverContext;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.StringFormulaManager;
import org.sosy_lab.java_smt.api.UFManager;
/**
* Abstract base class with helpful utilities for writing tests that use an SMT solver. It
* instantiates and closes the SMT solver before and after each test, and provides fields with
* direct access to the most relevant instances.
*
* <p>To run the tests using all available solvers, add the following code to your class:
*
* <pre>
* <code>
* {@literal @}Parameters(name="{0}")
* public static List{@literal <Object[]>} getAllSolvers() {
* return allSolversAsParameters();
* }
*
* {@literal @}Parameter(0)
* public Solvers solver;
*
* {@literal @}Override
* protected Solvers solverToUse() {
* return solver;
* }
* </code>
* </pre>
*
* {@link #assertThatFormula(BooleanFormula)} can be used to easily write assertions about formulas
* using Truth.
*
* <p>Test that rely on a theory that not all solvers support should call one of the {@code require}
* methods at the beginning.
*/
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification = "test code")
public abstract class SolverBasedTest0 {
protected Configuration config;
protected final LogManager logger = LogManager.createTestLogManager();
protected SolverContextFactory factory;
protected SolverContext context;
protected FormulaManager mgr;
protected BooleanFormulaManager bmgr;
protected UFManager fmgr;
protected IntegerFormulaManager imgr;
protected @Nullable RationalFormulaManager rmgr;
protected @Nullable BitvectorFormulaManager bvmgr;
protected @Nullable QuantifiedFormulaManager qmgr;
protected @Nullable ArrayFormulaManager amgr;
protected @Nullable FloatingPointFormulaManager fpmgr;
protected @Nullable StringFormulaManager smgr;
protected @Nullable EnumerationFormulaManager emgr;
protected ShutdownManager shutdownManager = ShutdownManager.create();
protected ShutdownNotifier shutdownNotifierToUse() {
return shutdownManager.getNotifier();
}
/**
* Return the solver to use in this test. The default is SMTInterpol because it's the only solver
* guaranteed on all platforms. Overwrite to specify a different solver.
*/
protected Solvers solverToUse() {
return Solvers.SMTINTERPOL;
}
protected ConfigurationBuilder createTestConfigBuilder() {
return Configuration.builder().setOption("solver.solver", solverToUse().toString());
}
@Before
public final void initSolver() throws InvalidConfigurationException {
config = createTestConfigBuilder().build();
factory = new SolverContextFactory(config, logger, shutdownNotifierToUse());
try {
context = factory.generateContext();
} catch (InvalidConfigurationException e) {
assume()
.withMessage(e.getMessage())
.that(e)
.hasCauseThat()
.isNotInstanceOf(UnsatisfiedLinkError.class);
throw e;
}
mgr = context.getFormulaManager();
fmgr = mgr.getUFManager();
bmgr = mgr.getBooleanFormulaManager();
// Needed for Boolector tests (Does not support Integer Formulas)
try {
imgr = mgr.getIntegerFormulaManager();
} catch (UnsupportedOperationException e) {
imgr = null;
}
try {
rmgr = mgr.getRationalFormulaManager();
} catch (UnsupportedOperationException e) {
rmgr = null;
}
try {
bvmgr = mgr.getBitvectorFormulaManager();
} catch (UnsupportedOperationException e) {
bvmgr = null;
}
try {
qmgr = mgr.getQuantifiedFormulaManager();
} catch (UnsupportedOperationException e) {
qmgr = null;
}
try {
amgr = mgr.getArrayFormulaManager();
} catch (UnsupportedOperationException e) {
amgr = null;
}
try {
fpmgr = mgr.getFloatingPointFormulaManager();
} catch (UnsupportedOperationException e) {
fpmgr = null;
}
try {
smgr = mgr.getStringFormulaManager();
} catch (UnsupportedOperationException e) {
smgr = null;
}
try {
emgr = mgr.getEnumerationFormulaManager();
} catch (UnsupportedOperationException e) {
emgr = null;
}
}
@After
public final void closeSolver() {
if (context != null) {
context.close();
}
}
/** Skip test if the solver does not support integers. */
protected final void requireIntegers() {
assume()
.withMessage("Solver %s does not support the theory of integers", solverToUse())
.that(imgr)
.isNotNull();
}
/** Skip test if the solver does not support rationals. */
protected final void requireRationals() {
assume()
.withMessage("Solver %s does not support the theory of rationals", solverToUse())
.that(rmgr)
.isNotNull();
}
/** Skip test if the solver does not support bitvectors. */
protected final void requireBitvectors() {
assume()
.withMessage("Solver %s does not support the theory of bitvectors", solverToUse())
.that(bvmgr)
.isNotNull();
}
protected final void requireBitvectorToInt() {
assume()
.withMessage(
"Solver %s does not yet support the conversion between bitvectors and integers",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.YICES2);
}
/** Skip test if the solver does not support quantifiers. */
protected final void requireQuantifiers() {
assume()
.withMessage("Solver %s does not support quantifiers", solverToUse())
.that(qmgr)
.isNotNull();
}
/** Skip test if the solver does not support arrays. */
protected final void requireArrays() {
assume()
.withMessage("Solver %s does not support the theory of arrays", solverToUse())
.that(amgr)
.isNotNull();
}
protected final void requireFloats() {
assume()
.withMessage("Solver %s does not support the theory of floats", solverToUse())
.that(fpmgr)
.isNotNull();
}
/** Skip test if the solver does not support strings. */
protected final void requireStrings() {
assume()
.withMessage("Solver %s does not support the theory of strings", solverToUse())
.that(smgr)
.isNotNull();
}
/** Skip test if the solver does not support enumeration theory. */
protected final void requireEnumeration() {
assume()
.withMessage("Solver %s does not support the theory of enumerations", solverToUse())
.that(emgr)
.isNotNull();
}
/** Skip test if the solver does not support optimization. */
protected final void requireOptimization() {
try {
context.newOptimizationProverEnvironment().close();
} catch (UnsupportedOperationException e) {
assume()
.withMessage("Solver %s does not support optimization", solverToUse())
.that(e)
.isNull();
}
}
protected final void requireInterpolation() {
try {
context.newProverEnvironmentWithInterpolation().close();
} catch (UnsupportedOperationException e) {
assume()
.withMessage("Solver %s does not support interpolation", solverToUse())
.that(e)
.isNull();
}
}
protected void requireParser() {
assume()
.withMessage("Solver %s does not support parsing formulae", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.BOOLECTOR, Solvers.YICES2, Solvers.CVC5);
}
protected void requireModel() {
/*assume()
.withMessage("Solver %s does not support model generation in a usable way", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);*/
}
protected void requireVisitor() {
assume()
.withMessage("Solver %s does not support formula visitor", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
}
protected void requireUnsatCore() {
assume()
.withMessage("Solver %s does not support unsat core generation", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
}
/**
* Use this for checking assertions about BooleanFormulas with Truth: <code>
* assertThatFormula(formula).is...()</code>.
*/
protected final BooleanFormulaSubject assertThatFormula(BooleanFormula formula) {
return assertUsing(context).that(formula);
}
/**
* Use this for checking assertions about ProverEnvironments with Truth: <code>
* assertThatEnvironment(stack).is...()</code>.
*
* <p>For new code, we suggest using {@link
* ProverEnvironmentSubject#assertThat(BasicProverEnvironment)} with a static import.
*/
protected final ProverEnvironmentSubject assertThatEnvironment(BasicProverEnvironment<?> prover) {
return assertThat(prover);
}
protected void evaluateInModel(
BooleanFormula constraint,
Formula formula,
Collection<Object> possibleExpectedValues,
Collection<Formula> possibleExpectedFormulas)
throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(constraint);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (formula instanceof BooleanFormula) {
Truth.assertThat(m.evaluate((BooleanFormula) formula)).isIn(possibleExpectedValues);
Truth.assertThat(m.evaluate(formula)).isIn(possibleExpectedValues);
} else if (formula instanceof IntegerFormula) {
Truth.assertThat(m.evaluate((IntegerFormula) formula)).isIn(possibleExpectedValues);
Truth.assertThat(m.evaluate(formula)).isIn(possibleExpectedValues);
} else if (formula instanceof RationalFormula) {
Truth.assertThat(m.evaluate((RationalFormula) formula)).isIn(possibleExpectedValues);
// assertThat(m.evaluate(formula)).isIn(possibleExpectedValues);
} else if (formula instanceof StringFormula) {
Truth.assertThat(m.evaluate((StringFormula) formula)).isIn(possibleExpectedValues);
Truth.assertThat(m.evaluate(formula)).isIn(possibleExpectedValues);
} else {
Truth.assertThat(m.evaluate(formula)).isIn(possibleExpectedValues);
}
// let's try to check evaluations. Actually the whole method is based on some default values
// in the solvers, because we do not use constraints for the evaluated formulas.
Formula eval = m.eval(formula);
if (eval != null) {
switch (solverToUse()) {
case Z3:
// ignore, Z3 provides arbitrary values
break;
case BOOLECTOR:
// ignore, Boolector provides no useful values
break;
default:
Truth.assertThat(eval).isIn(possibleExpectedFormulas);
}
}
}
}
}
@RunWith(Parameterized.class)
public abstract static class ParameterizedSolverBasedTest0 extends SolverBasedTest0 {
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
}
}
| 13,671 | 33.351759 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverConcurrencyTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableMap;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.ShutdownManager;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.ConfigurationBuilder;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BitvectorFormulaManager;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment;
import org.sosy_lab.java_smt.api.OptimizationProverEnvironment.OptStatus;
import org.sosy_lab.java_smt.api.SolverContext;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
@SuppressWarnings("resource")
@RunWith(Parameterized.class)
public class SolverConcurrencyTest {
private static final int NUMBER_OF_THREADS = 4;
private static final int TIMEOUT_SECONDS = 30;
/**
* As some Solvers are slower/faster, we choose an appropriate number of formulas to solve here.
*/
private static final ImmutableMap<Solvers, Integer> INTEGER_FORMULA_GEN =
ImmutableMap.of(
Solvers.SMTINTERPOL,
8,
Solvers.CVC4,
12,
Solvers.MATHSAT5,
12,
Solvers.PRINCESS,
8,
Solvers.Z3,
12);
private static final ImmutableMap<Solvers, Integer> BITVECTOR_FORMULA_GEN =
ImmutableMap.of(
Solvers.BOOLECTOR,
50,
Solvers.CVC4,
7,
Solvers.MATHSAT5,
50,
Solvers.PRINCESS,
5,
Solvers.Z3,
40);
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
protected Solvers solverToUse() {
return solver;
}
/**
* If UnsatisfiedLinkError (wrapped in InvalidConfigurationException) is thrown, abort the test.
* On some systems (like Windows), some solvers are not available.
*/
@Before
public void checkThatSolverIsAvailable() throws InvalidConfigurationException {
initSolver().close();
if (System.getProperty("os.name").toLowerCase(Locale.getDefault()).startsWith("win")) {
assume()
.withMessage("MathSAT5 is not reentant on Windows")
.that(solver)
.isNotEqualTo(Solvers.MATHSAT5);
}
}
private void requireConcurrentMultipleStackSupport() {
assume()
.withMessage("Solver does not support concurrent solving in multiple stacks")
.that(solver)
.isNoneOf(
Solvers.SMTINTERPOL,
Solvers.BOOLECTOR,
Solvers.MATHSAT5,
Solvers.Z3,
Solvers.PRINCESS,
Solvers.YICES2,
Solvers.CVC5);
}
private void requireIntegers() {
assume()
.withMessage("Solver does not support integers")
.that(solver)
.isNoneOf(Solvers.BOOLECTOR, Solvers.YICES2);
}
private void requireBitvectors() {
assume()
.withMessage("Solver does not support bitvectors")
.that(solver)
.isNoneOf(Solvers.SMTINTERPOL, Solvers.YICES2);
}
private void requireOptimization() {
assume()
.withMessage("Solver does not support optimization")
.that(solver)
.isNoneOf(
Solvers.SMTINTERPOL,
Solvers.BOOLECTOR,
Solvers.PRINCESS,
Solvers.CVC4,
Solvers.CVC5,
Solvers.YICES2);
}
/**
* Test concurrency of integers (while every thread creates its unique context on its own
* concurrently).
*/
@Test
public void testIntConcurrencyWithConcurrentContext() {
requireIntegers();
assertConcurrency(
"testIntConcurrencyWithConcurrentContext",
() -> {
SolverContext context = initSolver();
intConcurrencyTest(context);
closeSolver(context);
});
}
/**
* Test concurrency of bitvectors (while every thread creates its unique context on its own
* concurrently).
*/
@Test
public void testBvConcurrencyWithConcurrentContext() {
requireBitvectors();
assertConcurrency(
"testBvConcurrencyWithConcurrentContext",
() -> {
SolverContext context = initSolver();
bvConcurrencyTest(context);
closeSolver(context);
});
}
/** Helperclass to pack a SolverContext together with a Formula. */
private static class ContextAndFormula {
private final SolverContext context;
private final BooleanFormula formula;
private ContextAndFormula(SolverContext context, BooleanFormula formula) {
this.context = context;
this.formula = formula;
}
SolverContext getContext() {
return context;
}
BooleanFormula getFormula() {
return formula;
}
}
/**
* Test translation of formulas used on distinct contexts to a new, unrelated context. Every
* thread creates a context, generates a formula, those are collected and handed back to the main
* thread where they are translated to the main-thread context, anded and asserted.
*/
@Test
public void testFormulaTranslationWithConcurrentContexts()
throws InvalidConfigurationException, InterruptedException, SolverException {
requireIntegers();
// CVC4 does not support parsing and therefore no translation.
// Princess has a wierd bug
// TODO: Look into the Princess problem
assume()
.withMessage("Solver does not support translation of formulas")
.that(solver)
.isNoneOf(Solvers.CVC4, Solvers.PRINCESS, Solvers.CVC5);
ConcurrentLinkedQueue<ContextAndFormula> contextAndFormulaList = new ConcurrentLinkedQueue<>();
assertConcurrency(
"testFormulaTranslationWithConcurrentContexts",
() -> {
SolverContext context = initSolver();
FormulaManager mgr = context.getFormulaManager();
IntegerFormulaManager imgr = mgr.getIntegerFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
HardIntegerFormulaGenerator gen = new HardIntegerFormulaGenerator(imgr, bmgr);
BooleanFormula threadFormula = gen.generate(INTEGER_FORMULA_GEN.getOrDefault(solver, 9));
// We need to know the context from which the formula was created
contextAndFormulaList.add(new ContextAndFormula(context, threadFormula));
});
assertThat(contextAndFormulaList).hasSize(NUMBER_OF_THREADS);
SolverContext context = initSolver();
FormulaManager mgr = context.getFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
List<BooleanFormula> translatedFormulas = new ArrayList<>();
for (ContextAndFormula currentContAndForm : contextAndFormulaList) {
SolverContext threadedContext = currentContAndForm.getContext();
BooleanFormula threadedFormula = currentContAndForm.getFormula();
BooleanFormula translatedFormula =
mgr.translateFrom(threadedFormula, threadedContext.getFormulaManager());
translatedFormulas.add(translatedFormula);
threadedContext.close();
}
assertThat(translatedFormulas).hasSize(NUMBER_OF_THREADS);
BooleanFormula finalFormula = bmgr.and(translatedFormulas);
try (BasicProverEnvironment<?> stack = context.newProverEnvironment()) {
stack.push(finalFormula);
assertWithMessage(
"Test testFormulaTranslationWithConcurrentContexts() failed isUnsat() in the main"
+ " thread.")
.that(stack.isUnsat())
.isTrue();
}
}
/** Test concurrency with already present and unique context per thread. */
@SuppressWarnings("resource")
@Test
public void testIntConcurrencyWithoutConcurrentContext() throws InvalidConfigurationException {
requireIntegers();
assume()
.withMessage("Solver does not support concurrency without concurrent context.")
.that(solver)
.isNotEqualTo(Solvers.CVC5);
ConcurrentLinkedQueue<SolverContext> contextList = new ConcurrentLinkedQueue<>();
// Initialize contexts before using them in the threads
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
contextList.add(initSolver());
}
assertConcurrency(
"testIntConcurrencyWithoutConcurrentContext",
() -> {
SolverContext context = contextList.poll();
intConcurrencyTest(context);
closeSolver(context);
});
}
/** Test concurrency with already present and unique context per thread. */
@SuppressWarnings("resource")
@Test
public void testBvConcurrencyWithoutConcurrentContext() throws InvalidConfigurationException {
requireBitvectors();
assume()
.withMessage("Solver does not support concurrency without concurrent context.")
.that(solver)
.isNotEqualTo(Solvers.CVC5);
ConcurrentLinkedQueue<SolverContext> contextList = new ConcurrentLinkedQueue<>();
// Initialize contexts before using them in the threads
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
contextList.add(initSolver());
}
assertConcurrency(
"testBvConcurrencyWithoutConcurrentContext",
() -> {
SolverContext context = contextList.poll();
bvConcurrencyTest(context);
closeSolver(context);
});
}
@Test
public void testConcurrentOptimization() {
requireOptimization();
assume()
.withMessage("Solver does support optimization, but is not yet reentrant.")
.that(solver)
.isNotEqualTo(Solvers.MATHSAT5);
assertConcurrency(
"testConcurrentOptimization",
() -> {
SolverContext context = initSolver("solver.mathsat5.loadOptimathsat5", "true");
optimizationTest(context);
closeSolver(context);
});
}
/**
* Test solving of large formula on concurrent stacks in one context (Stacks are not created in
* the Threads).
*/
@Test
public void testConcurrentStack() throws InvalidConfigurationException, InterruptedException {
requireConcurrentMultipleStackSupport();
SolverContext context = initSolver();
FormulaManager mgr = context.getFormulaManager();
IntegerFormulaManager imgr = mgr.getIntegerFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
HardIntegerFormulaGenerator gen = new HardIntegerFormulaGenerator(imgr, bmgr);
ConcurrentLinkedQueue<BasicProverEnvironment<?>> proverList = new ConcurrentLinkedQueue<>();
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
BooleanFormula instance = gen.generate(INTEGER_FORMULA_GEN.getOrDefault(solver, 9));
BasicProverEnvironment<?> pe = context.newProverEnvironment();
pe.push(instance);
proverList.add(pe);
}
assertConcurrency(
"testConcurrentStack",
() -> {
BasicProverEnvironment<?> stack = proverList.poll();
assertWithMessage("Solver %s failed a concurrency test", solverToUse())
.that(stack.isUnsat())
.isTrue();
});
closeSolver(context);
}
/**
* Uses HardBitvectorFormulaGenerator for longer test-cases to assess concurrency problems. Length
* is very solver depended, so make sure you choose an appropriate number for the used solver.
* Make sure to not call this method with a SolverContext that does not support bitvectors! (No
* requireBitvector() because the exceptionList would collect it and throw an exception failing
* the test!).
*
* @param context used context for the test-thread (Do not reuse contexts!)
*/
private void bvConcurrencyTest(SolverContext context)
throws SolverException, InterruptedException {
FormulaManager mgr = context.getFormulaManager();
BitvectorFormulaManager bvmgr = mgr.getBitvectorFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
HardBitvectorFormulaGenerator gen = new HardBitvectorFormulaGenerator(bvmgr, bmgr);
BooleanFormula instance = gen.generate(BITVECTOR_FORMULA_GEN.getOrDefault(solver, 9));
try (BasicProverEnvironment<?> pe = context.newProverEnvironment()) {
pe.push(instance);
assertWithMessage("Solver %s failed a concurrency test", solverToUse())
.that(pe.isUnsat())
.isTrue();
}
}
/**
* Uses HardIntegerFormulaGenerator for longer test-cases to assess concurrency problems. Length
* is very solver depended, so make sure you choose an appropriate number for the used solver.
* Make sure to not call this method with a SolverContext that does not support integers! (No
* requireIntegers() because the exceptionList would collect it and throw an exception failing the
* test!).
*
* @param context used context for the test-thread (Do not reuse contexts unless you know what you
* are doing!)
*/
private void intConcurrencyTest(SolverContext context)
throws SolverException, InterruptedException {
FormulaManager mgr = context.getFormulaManager();
IntegerFormulaManager imgr = mgr.getIntegerFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
HardIntegerFormulaGenerator gen = new HardIntegerFormulaGenerator(imgr, bmgr);
BooleanFormula instance = gen.generate(INTEGER_FORMULA_GEN.getOrDefault(solver, 9));
try (BasicProverEnvironment<?> pe = context.newProverEnvironment()) {
pe.push(instance);
assertWithMessage("Solver %s failed a concurrency test", solverToUse())
.that(pe.isUnsat())
.isTrue();
}
}
/**
* Test that starts multiple threads that solve several problems such that they tend to not finish
* at the same time. Once a problem finishes, the formula is then send to another thread (with the
* context) and the sending thread starts solving a new problem (either send to it, or by
* generating a new one). The thread that just got the formula + context translates the formula
* into its own context once its finished (and send its formula to another context) and starts
* solving the formula it got send. This test is supposed to show the feasability of translating
* formulas with contexts in (concurrent) use.
*/
@Test
public void continuousRunningThreadFormulaTransferTranslateTest() {
requireIntegers();
// CVC4 does not support parsing and therefore no translation.
// Princess has a wierd bug
// TODO: Look into the Princess problem
assume()
.withMessage("Solver does not support translation of formulas")
.that(solver)
.isNoneOf(Solvers.CVC4, Solvers.CVC5, Solvers.PRINCESS);
// This is fine! We might access this more than once at a time,
// but that gives only access to the bucket, which is threadsafe.
AtomicReferenceArray<BlockingQueue<ContextAndFormula>> bucketQueue =
new AtomicReferenceArray<>(NUMBER_OF_THREADS);
// Init as many buckets as there are threads; each bucket generates an initial formula (such
// that
// they are differently hard to solve) depending on the uniqueId
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
BlockingQueue<ContextAndFormula> bucket = new LinkedBlockingQueue<>(NUMBER_OF_THREADS);
bucketQueue.set(i, bucket);
}
// Bind unique IDs to each thread with a (threadsafe) unique ID generator
final UniqueIdGenerator idGenerator = new UniqueIdGenerator();
// Take the formula from the bucket of itself, solve it, once solved give the formula to the
// bucket of the next thread (have a counter for in which bucket we transfered the formula and
// +1 the counter)
assertConcurrency(
"continuousRunningThreadFormulaTransferTranslateTest",
() -> {
// Start the threads such that they each get a unqiue id
final int id = idGenerator.getFreshId();
int nextBucket = (id + 1) % NUMBER_OF_THREADS;
final BlockingQueue<ContextAndFormula> ownBucket = bucketQueue.get(id);
SolverContext context = initSolver();
FormulaManager mgr = context.getFormulaManager();
IntegerFormulaManager imgr = mgr.getIntegerFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
HardIntegerFormulaGenerator gen = new HardIntegerFormulaGenerator(imgr, bmgr);
BooleanFormula threadFormula =
gen.generate(INTEGER_FORMULA_GEN.getOrDefault(solver, 9) - id);
try (BasicProverEnvironment<?> stack = context.newProverEnvironment()) {
// Repeat till the bucket counter reaches itself again
while (nextBucket != id) {
stack.push(threadFormula);
assertWithMessage(
"Test continuousRunningThreadFormulaTransferTranslateTest() "
+ "failed isUnsat() in thread with id: "
+ id
+ ".")
.that(stack.isUnsat())
.isTrue();
// Take another formula from its own bucket or wait for one.
bucketQueue.get(nextBucket).add(new ContextAndFormula(context, threadFormula));
// Translate the formula into its own context and start solving
ContextAndFormula newFormulaAndContext = ownBucket.take();
threadFormula =
mgr.translateFrom(
newFormulaAndContext.getFormula(),
newFormulaAndContext.getContext().getFormulaManager());
nextBucket = (nextBucket + 1) % NUMBER_OF_THREADS;
}
}
});
}
// As optimization is not used much at the moment this small test is ok
private void optimizationTest(SolverContext context)
throws InterruptedException, SolverException {
FormulaManager mgr = context.getFormulaManager();
IntegerFormulaManager imgr = mgr.getIntegerFormulaManager();
BooleanFormulaManager bmgr = mgr.getBooleanFormulaManager();
try (OptimizationProverEnvironment prover =
context.newOptimizationProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula obj = imgr.makeVariable("obj");
prover.addConstraint(
bmgr.and(
imgr.lessOrEquals(x, imgr.makeNumber(10)),
imgr.lessOrEquals(y, imgr.makeNumber(15)),
imgr.equal(obj, imgr.add(x, y)),
imgr.greaterOrEquals(imgr.subtract(x, y), imgr.makeNumber(1))));
int handle = prover.maximize(obj);
// Maximize for x.
OptStatus response = prover.check();
assertThat(response).isEqualTo(OptStatus.OPT);
// Check the value.
assertThat(prover.upper(handle, Rational.ZERO)).hasValue(Rational.ofString("19"));
try (Model model = prover.getModel()) {
BigInteger xValue = model.evaluate(x);
BigInteger objValue = model.evaluate(obj);
BigInteger yValue = model.evaluate(y);
assertThat(objValue).isEqualTo(BigInteger.valueOf(19));
assertThat(xValue).isEqualTo(BigInteger.valueOf(10));
assertThat(yValue).isEqualTo(BigInteger.valueOf(9));
}
}
}
/**
* Creates and returns a completely new SolverContext for the currently used solver (We need this
* to get more than one Context in 1 method in a controlled way).
*
* @param additionalOptions a list of pairs (key, value) for creating a new solver context.
* @return new and unique SolverContext for current solver (Parameter(0))
*/
private SolverContext initSolver(String... additionalOptions)
throws InvalidConfigurationException {
try {
ConfigurationBuilder options =
Configuration.builder().setOption("solver.solver", solverToUse().toString());
for (int i = 0; i < additionalOptions.length; i += 2) {
options.setOption(additionalOptions[i], additionalOptions[i + 1]);
}
Configuration config = options.build();
LogManager logger = LogManager.createTestLogManager();
ShutdownNotifier shutdownNotifier = ShutdownManager.create().getNotifier();
SolverContextFactory factory = new SolverContextFactory(config, logger, shutdownNotifier);
return factory.generateContext();
} catch (InvalidConfigurationException e) {
assume()
.withMessage(e.getMessage())
.that(e)
.hasCauseThat()
.isNotInstanceOf(UnsatisfiedLinkError.class);
throw e;
}
}
private void closeSolver(SolverContext context) {
if (context != null) {
context.close();
}
}
/**
* Synchronizes start and stop of a concurrency test with NUMBER_OF_THREADS threads. This method
* will make sure that all exceptions are collected and assessed at the end, as well as stop the
* execution after TIMEOUT_SECONDS seconds in case of a deadlock or long calculation.
*
* @param runnable A Runnable to be tested, make sure that it can be executed several times in
* parallel, i.e. no internal state except the solver itself.
* @param testName Name of the test for accurate error messages
*/
private static void assertConcurrency(String testName, Run runnable) {
final ExecutorService threadPool = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
final List<Throwable> exceptionsList = Collections.synchronizedList(new ArrayList<>());
// Waits for all threads to be started
final CountDownLatch allExecutorThreadsReady = new CountDownLatch(NUMBER_OF_THREADS);
// Syncs start of tests after all threads are already created
final CountDownLatch afterInitBlocker = new CountDownLatch(1);
// Syncs end of tests (And prevents Deadlocks in test-threads etc.)
final CountDownLatch allDone = new CountDownLatch(NUMBER_OF_THREADS);
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
@SuppressWarnings("unused")
Future<?> future =
threadPool.submit(
() -> {
allExecutorThreadsReady.countDown();
try {
afterInitBlocker.await();
runnable.run();
} catch (Throwable e) {
exceptionsList.add(e);
} finally {
allDone.countDown();
}
});
}
try {
assertWithMessage("Timeout initializing the Threads for " + testName)
.that(allExecutorThreadsReady.await(NUMBER_OF_THREADS * 20, TimeUnit.MILLISECONDS))
.isTrue();
afterInitBlocker.countDown();
assertWithMessage("Timeout in " + testName)
.that(allDone.await(TIMEOUT_SECONDS, TimeUnit.SECONDS))
.isTrue();
} catch (Throwable e) {
exceptionsList.add(e);
} finally {
threadPool.shutdownNow();
}
assertWithMessage("Test %s failed with exception(s): %s", testName, exceptionsList)
.that(exceptionsList.isEmpty())
.isTrue();
}
/** just a small lambda-compatible interface. */
private interface Run {
void run() throws SolverException, InterruptedException, InvalidConfigurationException;
}
}
| 25,068 | 37.987558 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverContextFactoryTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.base.StandardSystemProperty;
import com.google.common.truth.StandardSubjectBuilder;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.ShutdownManager;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.java_smt.SolverContextFactory;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.SolverContext;
/**
* This JUnit test class is mainly intended for automated CI checks on different operating systems,
* where a plain environment without pre-installed solvers is guaranteed.
*/
@RunWith(Parameterized.class)
public class SolverContextFactoryTest {
private static final String OS =
StandardSystemProperty.OS_NAME.value().toLowerCase(Locale.getDefault()).replace(" ", "");
private static final boolean IS_WINDOWS = OS.startsWith("windows");
private static final boolean IS_MAC = OS.startsWith("macos");
private static final boolean IS_LINUX = OS.startsWith("linux");
protected Configuration config;
protected final LogManager logger = LogManager.createTestLogManager();
protected ShutdownManager shutdownManager = ShutdownManager.create();
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
private Solvers solverToUse() {
return solver;
}
private void requireNoNativeLibrary() {
assume()
.withMessage("Solver %s requires to load a native library", solverToUse())
.that(solverToUse())
.isAnyOf(Solvers.SMTINTERPOL, Solvers.PRINCESS);
}
private void requireNativeLibrary() {
assume()
.withMessage("Solver %s requires to load a native library", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.SMTINTERPOL, Solvers.PRINCESS);
}
/**
* Let's allow to disable some checks on certain combinations of operating systems and solvers,
* because of missing support.
*
* <p>We update this list, whenever a new solver or operating system is added.
*/
private void requireSupportedOperatingSystem() {
StandardSubjectBuilder assume =
assume()
.withMessage(
"Solver %s is not yet supported in the operating system %s", solverToUse(), OS);
switch (solverToUse()) {
case SMTINTERPOL:
case PRINCESS:
// any operating system is allowed, Java is already available.
return;
case BOOLECTOR:
case CVC4:
case CVC5:
case YICES2:
assume.that(IS_LINUX).isTrue();
return;
case MATHSAT5:
assume.that(IS_LINUX || IS_WINDOWS).isTrue();
return;
case Z3:
assume.that(IS_LINUX || IS_WINDOWS || IS_MAC).isTrue();
return;
default:
throw new AssertionError("unexpected solver: " + solverToUse());
}
}
@Before
public final void initSolver() throws InvalidConfigurationException {
config = Configuration.builder().setOption("solver.solver", solverToUse().toString()).build();
}
@Test
public void createSolverContextFactoryWithDefaultLoader() throws InvalidConfigurationException {
requireSupportedOperatingSystem();
SolverContextFactory factory =
new SolverContextFactory(config, logger, shutdownManager.getNotifier());
try (SolverContext context = factory.generateContext()) {
@SuppressWarnings("unused")
FormulaManager mgr = context.getFormulaManager();
}
}
@Test
public void createSolverContextFactoryWithSystemLoader() throws InvalidConfigurationException {
requireNativeLibrary();
requireSupportedOperatingSystem();
// we assume that no native solvers are installed on the testing machine by default.
SolverContextFactory factory =
new SolverContextFactory(
config, logger, shutdownManager.getNotifier(), System::loadLibrary);
try (SolverContext context = factory.generateContext()) {
assert_().fail();
@SuppressWarnings("unused")
FormulaManager mgr = context.getFormulaManager();
} catch (InvalidConfigurationException e) {
assert_().that(e).hasCauseThat().isInstanceOf(UnsatisfiedLinkError.class);
}
}
@Test
public void createSolverContextFactoryWithSystemLoaderForJavaSolver()
throws InvalidConfigurationException {
requireNoNativeLibrary();
requireSupportedOperatingSystem();
SolverContextFactory factory =
new SolverContextFactory(
config, logger, shutdownManager.getNotifier(), System::loadLibrary);
try (SolverContext context = factory.generateContext()) {
@SuppressWarnings("unused")
FormulaManager mgr = context.getFormulaManager();
}
}
}
| 5,477 | 33.670886 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverContextTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
public class SolverContextTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void testMultipleContextClose() {
context.close();
context.close();
context.close();
context.close();
}
@Test
public void testFormulaAccessAfterClose() {
BooleanFormula term = bmgr.makeVariable("variable");
BooleanFormula term2 = bmgr.makeVariable("variable");
BooleanFormula term3 = bmgr.makeVariable("test");
BooleanFormula termTrue = bmgr.makeBoolean(true);
BooleanFormula termFalse = bmgr.makeBoolean(false);
int hash = term.hashCode();
context.close();
// After calling 'close()', it depends on the solver whether we can further access any formula.
// It would be nice to check for SegFault in a Junit test, but I do not know how to do that.
// For the remaining test, we try to execute as much as possible after closing the context.
// CVC5 does not allow any access after close()
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
assertThat(term).isEqualTo(term2);
assertThat(term).isNotEqualTo(term3);
assertThat(term).isNotEqualTo(termTrue);
assertThat(termFalse).isNotEqualTo(termTrue);
// Boolector allows nothing, lets abort here.
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.BOOLECTOR);
assertThat(term.hashCode()).isEqualTo(hash);
// MathSAT5 allow nothing, lets abort here.
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.MATHSAT5);
// Yices2 allows nothing, lets abort here.
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.YICES2);
// Z3 seems to allows simple operations, but not deterministically, so better lets abort here.
// Simple checks could even be ok (comparison against constants like TRUE/FALSE).
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
assertThat(bmgr.isTrue(term)).isFalse();
assertThat(bmgr.isFalse(term)).isFalse();
assertThat(bmgr.isTrue(termTrue)).isTrue();
assertThat(bmgr.isFalse(termFalse)).isTrue();
// try to access some data about formulae and managers
assertThat(term.toString()).isEqualTo("variable");
assertThat(term.hashCode()).isEqualTo(hash);
assertThat(term).isEqualTo(term2);
// For CVC4, we close the solver, however do not finalize and cleanup the terms,
// thus direct access is possible, operations are forbidden.
// See https://github.com/sosy-lab/java-smt/issues/169
assume()
.withMessage(
"Solver %s does not support to access formulae after closing the context",
solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC4);
// Java-based solvers allow more, i.e. they wait for GC, which is nice.
// try to access some managers
BooleanFormula notTerm = bmgr.not(term);
assertThat(bmgr.isTrue(notTerm)).isFalse();
assertThat(bmgr.isFalse(notTerm)).isFalse();
BooleanFormula opTerm = bmgr.and(notTerm, term2);
assertThat(bmgr.isTrue(opTerm)).isFalse();
assertThat(bmgr.isFalse(opTerm)).isFalse();
}
}
| 4,360 | 34.455285 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverFormulaIODeclarationsTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assert_;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.truth.Truth;
import java.util.EnumSet;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
public class SolverFormulaIODeclarationsTest
extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Before
public void checkThatSolverIsAvailable() {
requireParser();
}
@Test
public void parseDeclareInQueryTest1() {
String query = "(declare-fun var () Bool)(assert var)";
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariables(formula)).hasSize(1);
}
@Test
public void parseDeclareInQueryTest2() {
String query = "(declare-fun x () Int)(assert (= 0 x))";
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariables(formula)).hasSize(1);
}
@Test
public void parseDeclareInQueryTest3() {
String query = "(declare-fun foo (Int Int) Bool)(assert (foo 1 2))";
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariablesAndUFs(formula)).hasSize(1);
}
@Test
public void parseDeclareInQueryTest4() {
String query = "(declare-fun x () Int)(declare-fun foo (Int Int) Bool)(assert (foo x 2))";
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariablesAndUFs(formula)).hasSize(2);
}
@Test
public void parseDeclareAfterQueryTest1() {
String query = "(declare-fun var () Bool)(assert var)";
BooleanFormula formula = mgr.parse(query);
BooleanFormula var = bmgr.makeVariable("var");
Truth.assertThat(mgr.extractVariables(formula).values()).containsExactly(var);
}
@Test
public void parseDeclareAfterQueryTest2() {
String query = "(declare-fun x () Int)(assert (= 0 x))";
BooleanFormula formula = mgr.parse(query);
IntegerFormula var = imgr.makeVariable("x");
Truth.assertThat(mgr.extractVariables(formula).values()).containsExactly(var);
}
@Test
public void parseDeclareAfterQueryTest3() {
String query = "(declare-fun foo (Int Int) Bool)(assert (foo 1 2))";
BooleanFormula formula = mgr.parse(query);
BooleanFormula calledFoo =
fmgr.declareAndCallUF("foo", BooleanType, imgr.makeNumber(1), imgr.makeNumber(2));
Truth.assertThat(mgr.extractVariablesAndUFs(formula).values()).containsExactly(calledFoo);
}
@Test
public void parseDeclareAfterQueryTest4() {
String query = "(declare-fun x () Int)(declare-fun foo (Int Int) Bool)(assert (foo 1 x))";
BooleanFormula formula = mgr.parse(query);
IntegerFormula var = imgr.makeVariable("x");
BooleanFormula calledFoo = fmgr.declareAndCallUF("foo", BooleanType, imgr.makeNumber(1), var);
Truth.assertThat(mgr.extractVariablesAndUFs(formula).values()).containsExactly(var, calledFoo);
}
@Test
public void parseDeclareNeverTest1() {
String query = "(assert var)";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareNeverTest2() {
String query = "(assert (= 0 x))";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareNeverTest3() {
String query = "(assert (foo 1 2))";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareNeverTest4() {
String query = "(assert (foo 1 x))";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareBeforeTest() {
String query = "(assert var)";
BooleanFormula var = bmgr.makeVariable("var");
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariables(formula).values()).containsExactly(var);
}
@Test
public void parseDeclareRedundantTest1() {
IntegerFormula var = imgr.makeVariable("x");
String query = "(declare-fun x () Int)(declare-fun x () Int)(assert (= 0 x))";
if (EnumSet.of(Solvers.PRINCESS, Solvers.Z3).contains(solverToUse())) {
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
} else {
// some solvers are more tolerant for identical symbols.
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariables(formula).values()).containsExactly(var);
}
}
@Test
public void parseDeclareRedundantTest2() {
IntegerFormula var =
fmgr.declareAndCallUF("foo", IntegerType, imgr.makeNumber(1), imgr.makeNumber(2));
String query =
"(declare-fun foo (Int Int) Int)(declare-fun foo (Int Int) Int)(assert (= 0 (foo 1 2)))";
if (EnumSet.of(Solvers.PRINCESS, Solvers.Z3).contains(solverToUse())) {
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
} else {
// some solvers are more tolerant for identical symbols.
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariablesAndUFs(formula).values()).containsExactly(var);
}
}
@Test
public void parseDeclareConflictInQueryTest1() {
String query = "(declare-fun x () Bool)(declare-fun x () Int)(assert (= 0 x))";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareConflictInQueryTest2() {
String query = "(declare-fun x () Bool)(declare-fun x (Int Int) Bool)(assert (x 2 3))";
if (Solvers.Z3 != solverToUse()) {
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
}
@Test
public void parseDeclareConflictInQueryTest3() {
String query = "(declare-fun x (Int) Bool)(declare-fun x (Int) Int)(assert (x 0))";
if (Solvers.Z3 != solverToUse()) {
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
}
@Test
public void parseDeclareConflictBeforeQueryTest() {
@SuppressWarnings("unused")
IntegerFormula var = imgr.makeVariable("x");
String query = "(declare-fun x () Bool)(assert (= 0 x))";
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query));
}
@Test
public void parseDeclareConflictAfterQueryTest() {
String query = "(declare-fun x () Bool)(assert x)";
BooleanFormula formula = mgr.parse(query);
Truth.assertThat(mgr.extractVariables(formula).values()).hasSize(1);
if (!EnumSet.of(Solvers.PRINCESS, Solvers.Z3).contains(solverToUse())) {
assertThrows(IllegalArgumentException.class, () -> imgr.makeVariable("x"));
} else {
Truth.assertThat(mgr.extractVariables(formula).values())
.doesNotContain(imgr.makeVariable("x"));
}
}
@Test
public void parseDeclareOnceNotTwiceTest1() {
String query1 = "(declare-fun x () Bool)(assert x)";
String query2 = "(assert (not x))";
BooleanFormula formula1 = mgr.parse(query1);
Truth.assertThat(mgr.extractVariables(formula1).values()).hasSize(1);
BooleanFormula formula2 = mgr.parse(query2);
Truth.assertThat(mgr.extractVariables(formula2).values()).hasSize(1);
Truth.assertThat(mgr.extractVariables(formula1)).isEqualTo(mgr.extractVariables(formula2));
}
@Test
public void parseTwiceTest1() {
String query1 = "(declare-fun x () Bool)(assert x)";
String query2 = "(declare-fun x () Bool)(assert x)";
BooleanFormula formula1 = mgr.parse(query1);
Truth.assertThat(mgr.extractVariables(formula1).values()).hasSize(1);
BooleanFormula formula2 = mgr.parse(query2);
Truth.assertThat(mgr.extractVariables(formula2).values()).hasSize(1);
Truth.assertThat(formula1).isEqualTo(formula2);
}
@Test
public void parseDeclareOnceNotTwiceTest2() {
String query1 =
"(declare-fun x () Bool)(declare-fun foo (Int Int) Bool)(assert (= (foo 1 2) x))";
String query2 = "(assert (and (not x) (foo 3 4)))";
BooleanFormula formula1 = mgr.parse(query1);
Truth.assertThat(mgr.extractVariablesAndUFs(formula1).values()).hasSize(2);
BooleanFormula formula2 = mgr.parse(query2);
Truth.assertThat(mgr.extractVariablesAndUFs(formula2).values()).hasSize(2);
Truth.assertThat(mgr.extractVariablesAndUFs(formula1).keySet())
.isEqualTo(mgr.extractVariablesAndUFs(formula2).keySet());
}
@Test
public void parseDeclareOnceNotTwiceTest3() {
String query1 = "(declare-fun x () Bool)(declare-fun y () Bool)(assert x)";
String query2 = "(assert y)";
BooleanFormula formula1 = mgr.parse(query1);
Truth.assertThat(mgr.extractVariablesAndUFs(formula1).values()).hasSize(1);
if (Solvers.Z3 == solverToUse()) {
// "y" is unknown for the second query.
assertThrows(IllegalArgumentException.class, () -> mgr.parse(query2));
} else {
BooleanFormula formula2 = mgr.parse(query2);
Truth.assertThat(mgr.extractVariablesAndUFs(formula2).values()).hasSize(1);
}
}
@Test
public void parseAbbreviation() throws SolverException, InterruptedException {
requireBitvectors();
String query =
"(declare-fun bb () Bool)\n"
+ "(declare-fun b () Bool)\n"
+ "(declare-fun |f::v@2| () (_ BitVec 32))\n"
+ "(declare-fun A_a@ () (_ BitVec 32))\n"
+ "(declare-fun A_b@ () (_ BitVec 32))\n"
+ "(declare-fun i1 () (Array (_ BitVec 32) (_ BitVec 32)))\n"
+ "(declare-fun i2 () (Array (_ BitVec 32) (_ BitVec 32)))\n"
+ "(declare-fun i3 () (Array (_ BitVec 32) (_ BitVec 32)))\n"
+ "(declare-fun i4 () (Array (_ BitVec 32) (_ BitVec 32)))\n"
+ "(define-fun abbrev_9 () Bool (and\n"
+ " (not bb)\n"
+ " (= (_ bv0 32) A_a@)\n"
+ " (= (_ bv4 32) A_b@)\n"
+ " (= (bvurem A_b@ (_ bv4 32)) (_ bv0 32))\n"
+ " (bvslt (_ bv0 32) (bvadd A_b@ (_ bv4 32)))\n"
+ " (= (select i1 A_a@) (_ bv0 32))\n"
+ " (= (select i1 A_b@) (_ bv0 32))\n"
+ " (= i2 (store i1 A_b@ (_ bv1 32)))\n"
+ " (= i3 (store i2 A_a@ (_ bv5 32)))\n"
+ " (= i4 (store i3 A_a@ (_ bv4 32)))\n"
+ " (= |f::v@2| (bvsub (bvadd (_ bv4 32) (select i4 A_b@)) (_ bv4 32)))))\n"
+ "(assert (and\n"
+ " (not b) abbrev_9\n"
+ " (not (= |f::v@2| (_ bv1 32)))))";
BooleanFormula parsedQuery = mgr.parse(query);
assertThatFormula(parsedQuery).isUnsatisfiable();
assert_().that(mgr.extractVariables(parsedQuery)).hasSize(9);
assert_().that(mgr.extractVariablesAndUFs(parsedQuery)).hasSize(9);
}
}
| 11,061 | 38.088339 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverFormulaIOTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multiset;
import com.google.common.truth.TruthJUnit;
import java.util.function.Supplier;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
@SuppressWarnings("checkstyle:linelength")
public class SolverFormulaIOTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private static final String MATHSAT_DUMP1 =
"(set-info :source |printed by MathSAT|)\n"
+ "(declare-fun a () Bool)\n"
+ "(declare-fun b () Bool)\n"
+ "(declare-fun d () Bool)\n"
+ "(declare-fun e () Bool)\n"
+ "(define-fun .def_9 () Bool (= a b))\n"
+ "(define-fun .def_10 () Bool (not .def_9))\n"
+ "(define-fun .def_13 () Bool (and .def_10 d))\n"
+ "(define-fun .def_14 () Bool (or e .def_13))\n"
+ "(assert .def_14)";
private static final String MATHSAT_DUMP2 =
"(set-info :source |printed by MathSAT|)\n"
+ "(declare-fun a () Int)\n"
+ "(declare-fun b () Int)\n"
+ "(declare-fun c () Int)\n"
+ "(declare-fun q () Bool)\n"
+ "(declare-fun u () Bool)\n"
+ "(define-fun .def_15 () Int (* (- 1) c))\n"
+ "(define-fun .def_16 () Int (+ b .def_15))\n"
+ "(define-fun .def_17 () Int (+ a .def_16))\n"
+ "(define-fun .def_19 () Bool (= .def_17 0))\n"
+ "(define-fun .def_27 () Bool (= .def_19 q))\n"
+ "(define-fun .def_28 () Bool (not .def_27))\n"
+ "(define-fun .def_23 () Bool (<= b a))\n"
+ "(define-fun .def_29 () Bool (and .def_23 .def_28))\n"
+ "(define-fun .def_11 () Bool (= a b))\n"
+ "(define-fun .def_34 () Bool (and .def_11 .def_29))\n"
+ "(define-fun .def_30 () Bool (or u .def_29))\n"
+ "(define-fun .def_31 () Bool (and q .def_30))\n"
+ "(define-fun .def_35 () Bool (and .def_31 .def_34))\n"
+ "(assert .def_35)";
private static final String MATHSAT_DUMP3 =
"(set-info :source |printed by MathSAT|)\n"
+ "(declare-fun fun_b (Int) Bool)\n"
+ "(define-fun .def_11 () Bool (fun_b 1))\n"
+ "(assert .def_11)";
private static final String SMTINTERPOL_DUMP1 =
"(declare-fun d () Bool)\n"
+ "(declare-fun b () Bool)\n"
+ "(declare-fun a () Bool)\n"
+ "(declare-fun e () Bool)\n"
+ "(assert (or e (and (xor a b) d)))";
private static final String SMTINTERPOL_DUMP2 =
"(declare-fun b () Int)(declare-fun a () Int)\n"
+ "(declare-fun c () Int)\n"
+ "(declare-fun q () Bool)\n"
+ "(declare-fun u () Bool)\n"
+ "(assert (let ((.cse0 (xor q (= (+ a b) c))) (.cse1 (>= a b))) (and (or (and .cse0"
+ " .cse1) u) q (= a b) .cse0 .cse1)))";
private static final String Z3_DUMP1 =
"(declare-fun d () Bool)\n"
+ "(declare-fun b () Bool)\n"
+ "(declare-fun a () Bool)\n"
+ "(declare-fun e () Bool)\n"
+ "(assert (or e (and (xor a b) d)))";
private static final String Z3_DUMP2 =
"(declare-fun b () Int)\n"
+ "(declare-fun a () Int)\n"
+ "(declare-fun c () Int)\n"
+ "(declare-fun q () Bool)\n"
+ "(declare-fun u () Bool)\n"
+ "(assert (let (($x35 (and (xor q (= (+ a b) c)) (>= a b)))) (let (($x9 (= a b))) (and"
+ " (and (or $x35 u) q) (and $x9 $x35)))))";
@Test
public void varDumpTest() {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula a = bmgr.makeVariable("main::a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c1 = bmgr.xor(a, b);
BooleanFormula c2 = bmgr.xor(a, b);
BooleanFormula d = bmgr.and(c1, c2);
String formDump = mgr.dumpFormula(d).toString();
assertThat(formDump).contains("(declare-fun |main::a| () Bool)");
assertThat(formDump).contains("(declare-fun b () Bool)");
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void varDumpTest2() {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
// always true
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c1 = bmgr.xor(a, b);
BooleanFormula c2 = bmgr.and(a, b);
BooleanFormula d = bmgr.or(c1, c2);
BooleanFormula e = bmgr.and(a, d);
BooleanFormula x1 = bmgr.xor(a, b);
BooleanFormula x2 = bmgr.and(a, b);
BooleanFormula w = bmgr.or(x1, x2);
BooleanFormula v = bmgr.or(x1, b);
BooleanFormula branch1 = bmgr.and(d, e);
BooleanFormula branch2 = bmgr.and(w, v);
BooleanFormula branchComp = bmgr.or(branch1, branch2);
String formDump = mgr.dumpFormula(branchComp).toString();
assertThat(formDump).contains("(declare-fun a () Bool)");
assertThat(formDump).contains("(declare-fun b () Bool)");
// The serialization has to be parse-able.
checkThatDumpIsParseable(formDump);
}
@Test
public void valDumpTest() {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula tr1 = bmgr.makeBoolean(true);
BooleanFormula tr2 = bmgr.makeBoolean(true);
BooleanFormula fl1 = bmgr.makeBoolean(false);
BooleanFormula fl2 = bmgr.makeBoolean(false);
BooleanFormula valComp = bmgr.and(fl1, tr1);
BooleanFormula valComp2 = bmgr.and(fl1, tr1);
BooleanFormula valComp3 = bmgr.and(tr2, valComp);
BooleanFormula valComp4 = bmgr.and(fl2, valComp2);
BooleanFormula valComp5 = bmgr.or(valComp3, valComp4);
String formDump = mgr.dumpFormula(valComp5).toString();
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void intsDumpTest() {
requireIntegers();
IntegerFormula f1 = imgr.makeVariable("a");
IntegerFormula val = imgr.makeNumber(1);
BooleanFormula formula = imgr.equal(f1, val);
String formDump = mgr.dumpFormula(formula).toString();
// check that int variable is declared correctly + necessary assert that has to be there
assertThat(formDump).contains("(declare-fun a () Int)");
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void bvDumpTest() {
requireBitvectors();
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
BitvectorFormula f1 = bvmgr.makeVariable(8, "a");
BitvectorFormula val = bvmgr.makeBitvector(8, 1);
BooleanFormula formula = bvmgr.equal(f1, val);
String formDump = mgr.dumpFormula(formula).toString();
// check that int variable is declared correctly + necessary assert that has to be there
assertThat(formDump).contains("(declare-fun a () (_ BitVec 8))");
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void funcsDumpTest() {
requireIntegers();
IntegerFormula int1 = imgr.makeNumber(1);
IntegerFormula var = imgr.makeVariable("var_a");
FunctionDeclaration<IntegerFormula> funA =
fmgr.declareUF(
"fun_a", FormulaType.IntegerType, FormulaType.IntegerType, FormulaType.IntegerType);
IntegerFormula res1 = fmgr.callUF(funA, int1, var);
BooleanFormula formula = imgr.equal(res1, var);
String formDump = mgr.dumpFormula(formula).toString();
// check that function is dumped correctly + necessary assert that has to be there
assertThat(formDump).contains("(declare-fun fun_a (Int Int) Int)");
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void parseMathSatTestParseFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(MATHSAT_DUMP1, this::genBoolExpr);
}
@Test
public void parseMathSatTestExprFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(MATHSAT_DUMP1, this::genBoolExpr);
}
@Test
public void parseSmtinterpolTestParseFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(SMTINTERPOL_DUMP1, this::genBoolExpr);
}
@Test
public void parseSmtinterpolTestExprFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(SMTINTERPOL_DUMP1, this::genBoolExpr);
}
@Test
public void parseZ3TestParseFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(Z3_DUMP1, this::genBoolExpr);
}
@Test
public void parseZ3TestExprFirst1() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(Z3_DUMP1, this::genBoolExpr);
}
@Test
public void parseMathSatTestParseFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(MATHSAT_DUMP2, this::redundancyExprGen);
}
@Test
public void parseMathSatTestExprFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(MATHSAT_DUMP2, this::redundancyExprGen);
}
@Test
public void parseSmtinterpolSatTestParseFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(SMTINTERPOL_DUMP2, this::redundancyExprGen);
}
@Test
public void parseSmtinterpolSatTestExprFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(SMTINTERPOL_DUMP2, this::redundancyExprGen);
}
@Test
public void parseZ3SatTestParseFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(Z3_DUMP2, this::redundancyExprGen);
}
@Test
public void parseZ3SatTestExprFirst2() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(Z3_DUMP2, this::redundancyExprGen);
}
@Test
public void parseMathSatTestExprFirst3() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgExprFirst(MATHSAT_DUMP3, this::functionExprGen);
}
public void parseMathSatTestParseFirst3() throws SolverException, InterruptedException {
requireParser();
compareParseWithOrgParseFirst(MATHSAT_DUMP3, this::functionExprGen);
}
@Test
public void redundancyTest() {
assume()
.withMessage(
"Solver %s does not remove redundant sub formulae from formula dump.", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.YICES2, Solvers.CVC5);
assume()
.withMessage(
"Solver %s will fail this anyway since it bools are handled as bitvectors of length"
+ " one.",
solverToUse())
.that(solver)
.isNotEqualTo(Solvers.BOOLECTOR);
String formDump = mgr.dumpFormula(redundancyExprGen()).toString();
int count = Iterables.size(Splitter.on(">=").split(formDump)) - 1;
int count2 = Iterables.size(Splitter.on("<=").split(formDump)) - 1;
// Please avoid exponential overhead when printing a formula.
assertWithMessage(formDump + " does not contain <= or >= only once.")
.that(count == 1 || count2 == 1)
.isTrue();
}
@Test
public void funDeclareTest() {
requireIntegers();
IntegerFormula int1 = imgr.makeNumber(1);
IntegerFormula int2 = imgr.makeNumber(2);
FunctionDeclaration<IntegerFormula> funA =
fmgr.declareUF("fun_a", FormulaType.IntegerType, FormulaType.IntegerType);
FunctionDeclaration<IntegerFormula> funB =
fmgr.declareUF("fun_b", FormulaType.IntegerType, FormulaType.IntegerType);
IntegerFormula res1 = fmgr.callUF(funA, int1);
IntegerFormula res2 = fmgr.callUF(funB, int2);
IntegerFormula calc = imgr.add(res1, res2);
String formDump = mgr.dumpFormula(imgr.equal(calc, int1)).toString();
// check if dumped formula fits our specification
checkThatFunOnlyDeclaredOnce(formDump);
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
@Test
public void funDeclareTest2() {
requireIntegers();
IntegerFormula int1 = imgr.makeNumber(1);
IntegerFormula int2 = imgr.makeNumber(2);
FunctionDeclaration<IntegerFormula> funA =
fmgr.declareUF("fun_a", FormulaType.IntegerType, FormulaType.IntegerType);
IntegerFormula res1 = fmgr.callUF(funA, int1);
IntegerFormula res2 = fmgr.callUF(funA, int2);
IntegerFormula calc = imgr.add(res1, res2);
String formDump = mgr.dumpFormula(imgr.equal(calc, int1)).toString();
// check if dumped formula fits our specification
checkThatFunOnlyDeclaredOnce(formDump);
checkThatAssertIsInLastLine(formDump);
checkThatDumpIsParseable(formDump);
}
private void compareParseWithOrgExprFirst(String textToParse, Supplier<BooleanFormula> fun)
throws SolverException, InterruptedException {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
// check if input is correct
checkThatFunOnlyDeclaredOnce(textToParse);
checkThatAssertIsInLastLine(textToParse);
// actual test
BooleanFormula expr = fun.get();
BooleanFormula parsedForm = mgr.parse(textToParse);
assertThatFormula(parsedForm).isEquivalentTo(expr);
}
private void compareParseWithOrgParseFirst(String textToParse, Supplier<BooleanFormula> fun)
throws SolverException, InterruptedException {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
// check if input is correct
checkThatFunOnlyDeclaredOnce(textToParse);
checkThatAssertIsInLastLine(textToParse);
// actual test
BooleanFormula parsedForm = mgr.parse(textToParse);
BooleanFormula expr = fun.get();
assertThatFormula(parsedForm).isEquivalentTo(expr);
}
private void checkThatFunOnlyDeclaredOnce(String formDump) {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
Multiset<String> funDeclares = HashMultiset.create();
for (String line : Splitter.on('\n').split(formDump)) {
if (line.startsWith("(declare-fun ")) {
funDeclares.add(line.replaceAll("\\s+", ""));
}
}
// remove non-duplicates
funDeclares.entrySet().removeIf(pStringEntry -> pStringEntry.getCount() <= 1);
assertWithMessage("duplicate function declarations").that(funDeclares).isEmpty();
}
private void checkThatAssertIsInLastLine(String lines) {
// Boolector will fail this anyway since bools are bitvecs for btor
TruthJUnit.assume().that(solver).isNotEqualTo(Solvers.BOOLECTOR);
lines = lines.trim();
assertWithMessage("last line of <\n" + lines + ">")
.that(getLast(Splitter.on('\n').split(lines)))
.startsWith("(assert ");
}
@SuppressWarnings("CheckReturnValue")
private void checkThatDumpIsParseable(String dump) {
requireParser();
mgr.parse(dump);
}
private BooleanFormula genBoolExpr() {
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c = bmgr.xor(a, b);
BooleanFormula d = bmgr.makeVariable("d");
BooleanFormula e = bmgr.makeVariable("e");
BooleanFormula f = bmgr.and(c, d);
return bmgr.or(e, f);
}
private BooleanFormula redundancyExprGen() {
IntegerFormula i1 = imgr.makeVariable("a");
IntegerFormula i2 = imgr.makeVariable("b");
IntegerFormula erg = imgr.makeVariable("c");
BooleanFormula b1 = bmgr.makeVariable("q");
BooleanFormula b2 = bmgr.makeVariable("u");
// 1st execution
BooleanFormula f1 = imgr.equal(imgr.add(i1, i2), erg);
BooleanFormula comp1 = imgr.greaterOrEquals(i1, i2);
BooleanFormula x1 = bmgr.xor(b1, f1);
BooleanFormula comb1 = bmgr.and(x1, comp1);
// rest
BooleanFormula r1a = bmgr.or(comb1, b2);
BooleanFormula r1b = bmgr.and(r1a, b1);
// rest
BooleanFormula r2a = imgr.equal(i1, i2);
BooleanFormula r2b = bmgr.and(r2a, comb1);
return bmgr.and(r1b, r2b);
}
private BooleanFormula functionExprGen() {
IntegerFormula arg = imgr.makeNumber(1);
FunctionDeclaration<BooleanFormula> funA =
fmgr.declareUF("fun_b", FormulaType.BooleanType, FormulaType.IntegerType);
BooleanFormula res1 = fmgr.callUF(funA, arg);
return bmgr.and(res1, bmgr.makeBoolean(true));
}
}
| 17,734 | 37.05794 | 99 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverFormulaWithAssumptionsTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverException;
public class SolverFormulaWithAssumptionsTest
extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
/**
* Generate a prover environment depending on the parameter above. Can be overridden to
* parameterize the test.
*
* @throws InvalidConfigurationException overriding methods are allowed to throw this
*/
@SuppressWarnings({"unchecked", "rawtypes", "CheckReturnValue"})
protected <T> InterpolatingProverEnvironment<T> newEnvironmentForTest()
throws InvalidConfigurationException, SolverException, InterruptedException {
// check if we support assumption-solving
try (InterpolatingProverEnvironment<?> env = context.newProverEnvironmentWithInterpolation()) {
env.isUnsatWithAssumptions(ImmutableList.of());
} catch (UnsupportedOperationException e) {
assume()
.withMessage("Solver %s does not support assumption-solving", solverToUse())
.that(e)
.isNull();
}
return (InterpolatingProverEnvironment<T>) context.newProverEnvironmentWithInterpolation();
}
@Test
@SuppressWarnings("CheckReturnValue")
public <T> void basicAssumptionsTest()
throws SolverException, InterruptedException, InvalidConfigurationException {
requireInterpolation();
IntegerFormula v1 = imgr.makeVariable("v1");
IntegerFormula v2 = imgr.makeVariable("v2");
BooleanFormula suffix1 = bmgr.makeVariable("suffix1");
BooleanFormula suffix2 = bmgr.makeVariable("suffix2");
BooleanFormula suffix3 = bmgr.makeVariable("suffix3");
BooleanFormula term1 =
bmgr.or(
bmgr.and(imgr.equal(v1, imgr.makeNumber(BigDecimal.ONE)), bmgr.not(imgr.equal(v1, v2))),
suffix1);
BooleanFormula term2 = bmgr.or(imgr.equal(v2, imgr.makeNumber(BigDecimal.ONE)), suffix2);
BooleanFormula term3 =
bmgr.or(bmgr.not(imgr.equal(v1, imgr.makeNumber(BigDecimal.ONE))), suffix3);
try (InterpolatingProverEnvironment<T> env = newEnvironmentForTest()) {
T firstPartForInterpolant = env.push(term1);
env.push(term2);
env.push(term3);
assertThat(
env.isUnsatWithAssumptions(
ImmutableList.of(bmgr.not(suffix1), bmgr.not(suffix2), suffix3)))
.isTrue();
assertThat(env.getInterpolant(ImmutableList.of(firstPartForInterpolant)).toString())
.doesNotContain("suffix");
assertThat(
env.isUnsatWithAssumptions(
ImmutableList.of(bmgr.not(suffix1), bmgr.not(suffix3), suffix2)))
.isTrue();
assertThat(env.getInterpolant(ImmutableList.of(firstPartForInterpolant)).toString())
.doesNotContain("suffix");
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public <T> void assumptionsTest()
throws SolverException, InterruptedException, InvalidConfigurationException {
requireInterpolation();
int n = 5;
IntegerFormula x = imgr.makeVariable("x");
List<BooleanFormula> assignments = new ArrayList<>();
List<BooleanFormula> suffices = new ArrayList<>();
List<BooleanFormula> terms = new ArrayList<>();
for (int i = 0; i < n; i++) {
BooleanFormula a = imgr.equal(x, imgr.makeNumber(i));
BooleanFormula suffix = bmgr.makeVariable("suffix" + i);
assignments.add(a);
suffices.add(suffix);
terms.add(bmgr.or(a, suffix));
}
List<BooleanFormula> toCheckSat = new ArrayList<>();
List<BooleanFormula> toCheckUnsat = new ArrayList<>();
for (int i = 2; i < n; i++) {
try (InterpolatingProverEnvironment<T> env = newEnvironmentForTest()) {
List<T> ids = new ArrayList<>();
for (int j = 0; j < i; j++) {
ids.add(env.push(terms.get(j)));
}
// x==1 && x==2 ...
assertThat(
env.isUnsatWithAssumptions(Lists.transform(suffices.subList(0, i + 1), bmgr::not)))
.isTrue();
for (int j = 0; j < i; j++) {
BooleanFormula itp = env.getInterpolant(ImmutableList.of(ids.get(j)));
for (String var : mgr.extractVariables(itp).keySet()) {
assertThat(var).doesNotContain("suffix");
}
BooleanFormula contra = itp;
for (int k = 0; k < i; k++) {
if (k != j) {
contra = bmgr.and(contra, assignments.get(k));
}
}
toCheckSat.add(bmgr.implication(assignments.get(j), itp));
toCheckUnsat.add(contra);
}
}
for (BooleanFormula f : toCheckSat) {
assertThatFormula(f).isSatisfiable();
}
for (BooleanFormula f : toCheckUnsat) {
assertThatFormula(f).isUnsatisfiable();
}
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void assumptionsTest1() throws SolverException, InterruptedException {
/*
(declare-fun A () Bool)
(push 1)
(check-sat-assumptions (A))
(assert (not A))
(check-sat-assumptions (A))
*/
BooleanFormula a = bmgr.makeVariable("a");
try (ProverEnvironment pe = context.newProverEnvironment()) {
pe.push();
assertThat(pe.isUnsatWithAssumptions(ImmutableSet.of(a))).isFalse();
pe.addConstraint(bmgr.not(a));
assertThat(pe.isUnsatWithAssumptions(ImmutableSet.of(a))).isTrue();
}
}
}
| 6,253 | 34.134831 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverStackTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormulaManager;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
@RunWith(Parameterized.class)
@SuppressWarnings("resource")
public class SolverStackTest extends SolverBasedTest0 {
@Parameters(name = "{0} (interpolation={1}}")
public static List<Object[]> getAllCombinations() {
List<Object[]> result = new ArrayList<>();
for (Solvers solver : Solvers.values()) {
result.add(new Object[] {solver, false});
result.add(new Object[] {solver, true});
}
return result;
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Parameter(1)
public boolean useInterpolatingEnvironment;
/** Generate a prover environment depending on the parameter above. */
private BasicProverEnvironment<?> newEnvironmentForTest(ProverOptions... options) {
if (useInterpolatingEnvironment) {
requireInterpolation();
return context.newProverEnvironmentWithInterpolation(options);
} else {
return context.newProverEnvironment(options);
}
}
private static final UniqueIdGenerator index = new UniqueIdGenerator(); // to get different names
private void requireMultipleStackSupport() {
assume()
.withMessage("Solver does not support multiple stacks yet")
.that(solver)
.isNotEqualTo(Solvers.BOOLECTOR);
}
protected final void requireUfValuesInModel() {
assume()
.withMessage(
"Integration of solver does not support retrieving values for UFs from a model")
.that(solver)
.isNotEqualTo(Solvers.Z3);
}
@Test
public void simpleStackTestBool() throws SolverException, InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
int i = index.getFreshId();
BooleanFormula a = bmgr.makeVariable("bool_a" + i);
BooleanFormula b = bmgr.makeVariable("bool_b" + i);
BooleanFormula or = bmgr.or(a, b);
stack.push(or); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
BooleanFormula c = bmgr.makeVariable("bool_c" + i);
BooleanFormula d = bmgr.makeVariable("bool_d" + i);
BooleanFormula and = bmgr.and(c, d);
stack.push(and); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
BooleanFormula notOr = bmgr.not(or);
stack.push(notOr); // L3
assertThat(stack.size()).isEqualTo(3);
assertThat(stack).isUnsatisfiable(); // "or" AND "not or" --> UNSAT
stack.pop(); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
// we are lower than before creating c and d.
// however we assume that they are usable now (this violates SMTlib).
stack.push(and); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
stack.push(notOr); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isUnsatisfiable(); // "or" AND "not or" --> UNSAT
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
stack.pop(); // L0 empty stack
assertThat(stack.size()).isEqualTo(0);
}
@Test
public void singleStackTestInteger() throws SolverException, InterruptedException {
requireIntegers();
BasicProverEnvironment<?> env = newEnvironmentForTest();
simpleStackTestNum(imgr, env);
}
@Test
public void singleStackTestRational() throws SolverException, InterruptedException {
requireRationals();
BasicProverEnvironment<?> env = newEnvironmentForTest();
simpleStackTestNum(rmgr, env);
}
private <X extends NumeralFormula, Y extends X> void simpleStackTestNum(
NumeralFormulaManager<X, Y> nmgr, BasicProverEnvironment<?> stack)
throws SolverException, InterruptedException {
int i = index.getFreshId();
X a = nmgr.makeVariable("num_a" + i);
X b = nmgr.makeVariable("num_b" + i);
BooleanFormula leqAB = nmgr.lessOrEquals(a, b);
stack.push(leqAB); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
X c = nmgr.makeVariable("num_c" + i);
X d = nmgr.makeVariable("num_d" + i);
BooleanFormula eqCD = nmgr.lessOrEquals(c, d);
stack.push(eqCD); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
BooleanFormula gtAB = nmgr.greaterThan(a, b);
stack.push(gtAB); // L3
assertThat(stack.size()).isEqualTo(3);
assertThat(stack).isUnsatisfiable(); // "<=" AND ">" --> UNSAT
stack.pop(); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
// we are lower than before creating c and d.
// however we assume that they are usable now (this violates SMTlib).
stack.push(eqCD); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isSatisfiable();
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
stack.push(gtAB); // L2
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isUnsatisfiable(); // "or" AND "not or" --> UNSAT
stack.pop(); // L1
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
stack.pop(); // L0 empty stack
assertThat(stack.size()).isEqualTo(0);
}
@Test
public void stackTest() {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
assertThrows(RuntimeException.class, stack::pop);
}
@Test
public void stackTest2() throws InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
stack.push();
assertThat(stack.size()).isEqualTo(1);
stack.pop();
assertThat(stack.size()).isEqualTo(0);
}
@Test
public void stackTest3() throws InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
stack.push();
assertThat(stack.size()).isEqualTo(1);
stack.pop();
assertThat(stack.size()).isEqualTo(0);
stack.push();
assertThat(stack.size()).isEqualTo(1);
stack.pop();
assertThat(stack.size()).isEqualTo(0);
}
@Test
public void stackTest4() throws InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
stack.push();
stack.push();
assertThat(stack.size()).isEqualTo(2);
stack.pop();
stack.pop();
assertThat(stack.size()).isEqualTo(0);
}
@Test
public void largeStackUsageTest() throws InterruptedException, SolverException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
for (int i = 0; i < 20; i++) {
assertThat(stack.size()).isEqualTo(i);
stack.push();
stack.addConstraint(
bmgr.equivalence(bmgr.makeVariable("X" + i), bmgr.makeVariable("X" + (i + 1))));
stack.addConstraint(
bmgr.equivalence(bmgr.makeVariable("Y" + i), bmgr.makeVariable("Y" + (i + 1))));
stack.addConstraint(bmgr.equivalence(bmgr.makeVariable("X" + i), bmgr.makeVariable("Y" + i)));
}
assertThat(stack.isUnsat()).isFalse();
}
@Test
public void largerStackUsageTest() throws InterruptedException, SolverException {
assume()
.withMessage("Solver does not support larger stacks yet")
.that(solver)
.isNotEqualTo(Solvers.PRINCESS);
BasicProverEnvironment<?> stack = newEnvironmentForTest();
for (int i = 0; i < 1000; i++) {
assertThat(stack.size()).isEqualTo(i);
stack.push();
stack.addConstraint(
bmgr.equivalence(bmgr.makeVariable("X" + i), bmgr.makeVariable("X" + (i + 1))));
stack.addConstraint(
bmgr.equivalence(bmgr.makeVariable("Y" + i), bmgr.makeVariable("Y" + (i + 1))));
stack.addConstraint(bmgr.equivalence(bmgr.makeVariable("X" + i), bmgr.makeVariable("Y" + i)));
}
assertThat(stack.isUnsat()).isFalse();
}
@Test
public void stackTest5() throws InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
stack.push();
stack.pop();
assertThat(stack.size()).isEqualTo(0);
assertThrows(RuntimeException.class, stack::pop);
}
@Test
public void stackTestUnsat() throws InterruptedException, SolverException {
BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS);
assertThat(stack).isSatisfiable();
stack.push();
stack.addConstraint(bmgr.makeFalse());
assertThat(stack).isUnsatisfiable();
stack.push();
stack.addConstraint(bmgr.makeFalse());
assertThat(stack.size()).isEqualTo(2);
assertThat(stack).isUnsatisfiable();
stack.pop();
assertThat(stack).isUnsatisfiable();
stack.pop();
assertThat(stack.size()).isEqualTo(0);
assertThat(stack).isSatisfiable();
}
@Test
public void stackTestUnsat2() throws InterruptedException, SolverException {
BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS);
assertThat(stack).isSatisfiable();
stack.push();
stack.addConstraint(bmgr.makeTrue());
assertThat(stack).isSatisfiable();
stack.push();
stack.addConstraint(bmgr.makeFalse());
assertThat(stack).isUnsatisfiable();
stack.push();
assertThat(stack.size()).isEqualTo(3);
stack.addConstraint(bmgr.makeFalse());
assertThat(stack).isUnsatisfiable();
stack.pop();
assertThat(stack).isUnsatisfiable();
stack.pop();
assertThat(stack).isSatisfiable();
stack.pop();
assertThat(stack.size()).isEqualTo(0);
assertThat(stack).isSatisfiable();
}
/** Create a symbol on a level and pop this level. Symbol must remain valid and usable! */
@SuppressWarnings("unused")
@Test
public void symbolsOnStackTest() throws InterruptedException, SolverException {
requireModel();
BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS);
stack.push();
BooleanFormula q1 = bmgr.makeVariable("q");
stack.addConstraint(q1);
assertThat(stack).isSatisfiable();
Model m1 = stack.getModel();
assertThat(m1).isNotEmpty();
stack.pop();
stack.push();
BooleanFormula q2 = bmgr.makeVariable("q");
assertThat(q2).isEqualTo(q1);
stack.addConstraint(q1);
assertThat(stack).isSatisfiable();
Model m2 = stack.getModel();
assertThat(m2).isNotEmpty();
stack.pop();
}
@Test
public void constraintTestBool1() throws SolverException, InterruptedException {
BooleanFormula a = bmgr.makeVariable("bool_a");
try (BasicProverEnvironment<?> stack = newEnvironmentForTest()) {
stack.addConstraint(a);
assertThat(stack.size()).isEqualTo(0);
assertThat(stack).isSatisfiable();
}
try (BasicProverEnvironment<?> stack2 = newEnvironmentForTest()) {
stack2.addConstraint(bmgr.not(a));
assertThat(stack2.size()).isEqualTo(0);
assertThat(stack2).isSatisfiable();
}
}
@Test
public void constraintTestBool2() throws SolverException, InterruptedException {
BooleanFormula a = bmgr.makeVariable("bool_a");
try (BasicProverEnvironment<?> stack = newEnvironmentForTest()) {
stack.push(a);
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
}
try (BasicProverEnvironment<?> stack2 = newEnvironmentForTest()) {
stack2.addConstraint(bmgr.not(a));
assertThat(stack2.size()).isEqualTo(0);
assertThat(stack2).isSatisfiable();
}
}
@Test
public void constraintTestBool3() throws SolverException, InterruptedException {
BooleanFormula a = bmgr.makeVariable("bool_a");
try (BasicProverEnvironment<?> stack = newEnvironmentForTest()) {
stack.push(a);
assertThat(stack.size()).isEqualTo(1);
assertThat(stack).isSatisfiable();
}
try (BasicProverEnvironment<?> stack2 = newEnvironmentForTest()) {
assertThat(stack2.size()).isEqualTo(0);
assertThrows(RuntimeException.class, stack2::pop);
}
}
@Test
public void constraintTestBool4() throws SolverException, InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
stack.addConstraint(bmgr.makeVariable("bool_a"));
assertThat(stack).isSatisfiable();
assertThat(stack.size()).isEqualTo(0);
assertThrows(RuntimeException.class, stack::pop);
}
@Test
public void satTestBool5() throws SolverException, InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest();
assertThat(stack.size()).isEqualTo(0);
assertThat(stack).isSatisfiable();
}
@Test
public void dualStackTest() throws SolverException, InterruptedException {
requireMultipleStackSupport();
BooleanFormula a = bmgr.makeVariable("bool_a");
BooleanFormula not = bmgr.not(a);
BasicProverEnvironment<?> stack1 = newEnvironmentForTest();
stack1.push(a); // L1
stack1.push(a); // L2
assertThat(stack1.size()).isEqualTo(2);
BasicProverEnvironment<?> stack2 = newEnvironmentForTest();
stack1.pop(); // L1
stack1.pop(); // L0
assertThat(stack1.size()).isEqualTo(0);
stack1.push(a); // L1
assertThat(stack1.size()).isEqualTo(1);
assertThat(stack1).isSatisfiable();
stack2.push(not); // L1
assertThat(stack2.size()).isEqualTo(1);
assertThat(stack2).isSatisfiable();
stack1.pop(); // L0
stack2.pop(); // L0
assertThat(stack1.size()).isEqualTo(0);
assertThat(stack2.size()).isEqualTo(0);
}
@Test
public void dualStackTest2() throws SolverException, InterruptedException {
requireMultipleStackSupport();
BooleanFormula a = bmgr.makeVariable("bool_a");
BooleanFormula not = bmgr.not(a);
BasicProverEnvironment<?> stack1 = newEnvironmentForTest();
BasicProverEnvironment<?> stack2 = newEnvironmentForTest();
stack1.push(a); // L1
stack1.push(bmgr.makeBoolean(true)); // L2
assertThat(stack1).isSatisfiable();
stack2.push(not); // L1
assertThat(stack1.size()).isEqualTo(2);
assertThat(stack2.size()).isEqualTo(1);
assertThat(stack2).isSatisfiable();
stack1.pop(); // L1
assertThat(stack1).isSatisfiable();
stack1.pop(); // L1
assertThat(stack1).isSatisfiable();
stack2.pop(); // L1
assertThat(stack2).isSatisfiable();
assertThat(stack1).isSatisfiable();
assertThat(stack1.size()).isEqualTo(0);
assertThat(stack2.size()).isEqualTo(0);
}
@Test
public void multiStackTest() throws SolverException, InterruptedException {
requireMultipleStackSupport();
int limit = 10;
BooleanFormula a = bmgr.makeVariable("bool_a");
BooleanFormula not = bmgr.not(a);
List<BasicProverEnvironment<?>> stacks = new ArrayList<>();
for (int i = 0; i < limit; i++) {
stacks.add(newEnvironmentForTest());
}
for (int i = 0; i < limit; i++) {
stacks.get(i).push(a); // L1
stacks.get(i).push(bmgr.makeBoolean(true));
assertThat(stacks.get(i)).isSatisfiable();
assertThat(stacks.get(i).size()).isEqualTo(2);
stacks.get(i).push();
stacks.get(i).push();
assertThat(stacks.get(i).size()).isEqualTo(4);
stacks.get(i).pop();
stacks.get(i).pop();
}
for (int i = 0; i < limit; i++) {
stacks.get(i).push(not);
assertThat(stacks.get(i)).isUnsatisfiable();
assertThat(stacks.get(i).size()).isEqualTo(3);
stacks.get(i).pop();
assertThat(stacks.get(i).size()).isEqualTo(2);
}
for (int i = 0; i < limit; i++) {
stacks.get(i).pop();
assertThat(stacks.get(i).size()).isEqualTo(1);
stacks.get(i).close();
}
}
@Test(expected = IllegalStateException.class)
@SuppressWarnings("CheckReturnValue")
public void avoidDualStacksIfNotSupported() throws InterruptedException {
assume()
.withMessage("Solver does not support multiple stacks yet")
.that(solver)
.isEqualTo(Solvers.BOOLECTOR);
BasicProverEnvironment<?> stack1 = newEnvironmentForTest();
stack1.push(bmgr.makeTrue());
// creating a new environment is not allowed with non-empty stack -> fail
newEnvironmentForTest();
}
/**
* This test checks that an SMT solver uses "global declarations": regardless of the stack at
* declaration time, declarations always live for the full lifetime of the solver (i.e., they do
* not get deleted on pop()). This is contrary to the SMTLib standard, but required by us, e.g.
* for BMC with induction (where we create new formulas while there is something on the stack).
*/
@Test
public void dualStackGlobalDeclarations() throws SolverException, InterruptedException {
// Create non-empty stack
BasicProverEnvironment<?> stack1 = newEnvironmentForTest();
stack1.push(bmgr.makeVariable("bool_a"));
// Declare b while non-empty stack exists
final String varName = "bool_b";
final BooleanFormula b = bmgr.makeVariable(varName);
// Clear stack (without global declarations b gets deleted)
stack1.push(b);
assertThat(stack1).isSatisfiable();
stack1.pop();
stack1.pop();
assertThat(stack1.size()).isEqualTo(0);
stack1.close();
assertThrows(IllegalStateException.class, stack1::size);
// Check that "b" (the reference to the old formula)
// is equivalent to a new formula with the same variable
assertThatFormula(b).isEquivalentTo(bmgr.makeVariable(varName));
}
@Test
@SuppressWarnings("CheckReturnValue")
public void modelForUnsatFormula() throws SolverException, InterruptedException {
requireIntegers();
try (BasicProverEnvironment<?> stack = newEnvironmentForTest()) {
stack.push(imgr.greaterThan(imgr.makeVariable("a"), imgr.makeNumber(0)));
stack.push(imgr.lessThan(imgr.makeVariable("a"), imgr.makeNumber(0)));
assertThat(stack).isUnsatisfiable();
assertThrows(Exception.class, stack::getModel);
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void modelForUnsatFormula2() throws SolverException, InterruptedException {
requireIntegers();
try (BasicProverEnvironment<?> stack = newEnvironmentForTest()) {
stack.push(imgr.greaterThan(imgr.makeVariable("a"), imgr.makeNumber(0)));
assertThat(stack).isSatisfiable();
stack.push(imgr.lessThan(imgr.makeVariable("a"), imgr.makeNumber(0)));
assertThat(stack).isUnsatisfiable();
assertThrows(Exception.class, stack::getModel);
}
}
@Test
public void modelForSatFormula() throws SolverException, InterruptedException {
requireIntegers();
try (BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS)) {
IntegerFormula a = imgr.makeVariable("a");
stack.push(imgr.greaterThan(a, imgr.makeNumber(0)));
stack.push(imgr.lessThan(a, imgr.makeNumber(2)));
assertThat(stack).isSatisfiable();
Model model = stack.getModel();
assertThat(model.evaluate(a)).isEqualTo(BigInteger.ONE);
}
}
@Test
public void modelForSatFormulaWithLargeValue() throws SolverException, InterruptedException {
requireIntegers();
try (BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS)) {
BigInteger val = BigInteger.TEN.pow(1000);
IntegerFormula a = imgr.makeVariable("a");
stack.push(imgr.equal(a, imgr.makeNumber(val)));
assertThat(stack).isSatisfiable();
Model model = stack.getModel();
assertThat(model.evaluate(a)).isEqualTo(val);
}
}
@Test
public void modelForSatFormulaWithUF() throws SolverException, InterruptedException {
requireIntegers();
try (BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS)) {
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula varA = imgr.makeVariable("a");
IntegerFormula varB = imgr.makeVariable("b");
stack.push(imgr.equal(varA, zero));
stack.push(imgr.equal(varB, zero));
FunctionDeclaration<IntegerFormula> uf =
fmgr.declareUF("uf", FormulaType.IntegerType, FormulaType.IntegerType);
stack.push(imgr.equal(fmgr.callUF(uf, varA), zero));
stack.push(imgr.equal(fmgr.callUF(uf, varB), zero));
assertThat(stack).isSatisfiable();
Model model = stack.getModel();
// actual type of object is not defined, thus do string matching:
assertThat(model.evaluate(varA)).isEqualTo(BigInteger.ZERO);
assertThat(model.evaluate(varB)).isEqualTo(BigInteger.ZERO);
requireUfValuesInModel();
assertThat(model.evaluate(fmgr.callUF(uf, imgr.makeNumber(BigDecimal.ZERO))))
.isEqualTo(BigInteger.ZERO);
}
}
@Test
@SuppressWarnings("resource")
public void multiCloseTest() throws SolverException, InterruptedException {
BasicProverEnvironment<?> stack = newEnvironmentForTest(ProverOptions.GENERATE_MODELS);
try {
// do something on the stack
stack.push();
stack.pop();
stack.push(bmgr.equivalence(bmgr.makeVariable("a"), bmgr.makeTrue()));
assertThat(stack).isSatisfiable();
stack.push();
} finally {
// close the stack several times, closing should be idempotent
for (int i = 0; i < 10; i++) {
stack.close();
assertThrows(IllegalStateException.class, stack::size);
assertThrows(IllegalStateException.class, stack::push);
assertThrows(IllegalStateException.class, stack::pop);
}
}
}
}
| 23,004 | 32.731672 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverTacticsTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.TruthJUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.Tactic;
import org.sosy_lab.java_smt.api.visitors.BooleanFormulaVisitor;
@SuppressWarnings("LocalVariableName")
public class SolverTacticsTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void nnfTacticDefaultTest1() throws SolverException, InterruptedException {
requireVisitor();
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula not_a_b = bmgr.not(bmgr.equivalence(a, b));
BooleanFormula nnf = mgr.applyTactic(not_a_b, Tactic.NNF);
assertThatFormula(nnf).isEquivalentTo(not_a_b);
NNFChecker checker = new NNFChecker(mgr);
bmgr.visit(nnf, checker);
assertThat(checker.isInNNF()).isTrue();
}
@Test
public void nnfTacticDefaultTest2() throws SolverException, InterruptedException {
requireVisitor();
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c = bmgr.makeVariable("c");
BooleanFormula not_ITE_a_b_c = bmgr.not(bmgr.ifThenElse(a, b, c));
BooleanFormula nnf = mgr.applyTactic(not_ITE_a_b_c, Tactic.NNF);
assertThatFormula(nnf).isEquivalentTo(not_ITE_a_b_c);
NNFChecker checker = new NNFChecker(mgr);
checker.visit(nnf);
assertThat(checker.isInNNF()).isTrue();
}
@Test
public void cnfTacticDefaultTest1() throws SolverException, InterruptedException {
TruthJUnit.assume().that(solver).isEqualTo(Solvers.Z3);
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula equiv_a_b = bmgr.equivalence(a, b);
BooleanFormula not_equiv_a_b = bmgr.not(equiv_a_b);
BooleanFormula cnf_equiv_a_b = mgr.applyTactic(equiv_a_b, Tactic.TSEITIN_CNF);
assertThatFormula(cnf_equiv_a_b).isEquisatisfiableTo(equiv_a_b);
CNFChecker checker = new CNFChecker(mgr);
checker.visit(cnf_equiv_a_b);
assertThat(checker.isInCNF()).isTrue();
BooleanFormula cnf_not_equiv_a_b = mgr.applyTactic(not_equiv_a_b, Tactic.TSEITIN_CNF);
assertThatFormula(cnf_not_equiv_a_b).isEquisatisfiableTo(not_equiv_a_b);
checker = new CNFChecker(mgr);
checker.visit(cnf_not_equiv_a_b);
assertThat(checker.isInCNF()).isTrue();
}
@Test
public void cnfTacticDefaultTest2() throws SolverException, InterruptedException {
TruthJUnit.assume().that(solver).isEqualTo(Solvers.Z3);
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula c = bmgr.makeVariable("c");
BooleanFormula ITE_a_b_c = bmgr.ifThenElse(a, b, c);
BooleanFormula not_ITE_a_b_c = bmgr.not(bmgr.ifThenElse(a, b, c));
BooleanFormula cnf_ITE_a_b_c = mgr.applyTactic(ITE_a_b_c, Tactic.TSEITIN_CNF);
assertThatFormula(cnf_ITE_a_b_c).isEquisatisfiableTo(ITE_a_b_c);
CNFChecker checker = new CNFChecker(mgr);
checker.visit(cnf_ITE_a_b_c);
assertThat(checker.isInCNF()).isTrue();
BooleanFormula cnf_not_ITE_a_b_c = mgr.applyTactic(not_ITE_a_b_c, Tactic.TSEITIN_CNF);
assertThatFormula(cnf_not_ITE_a_b_c).isEquisatisfiableTo(not_ITE_a_b_c);
checker = new CNFChecker(mgr);
checker.visit(cnf_not_ITE_a_b_c);
assertThat(checker.isInCNF()).isTrue();
}
@Test
public void cnfTacticDefaultTest3() throws SolverException, InterruptedException {
TruthJUnit.assume().that(solver).isEqualTo(Solvers.Z3);
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula y = bmgr.makeVariable("y");
BooleanFormula z = bmgr.makeVariable("z");
BooleanFormula w = bmgr.makeVariable("w");
BooleanFormula u = bmgr.makeVariable("u");
BooleanFormula v = bmgr.makeVariable("v");
List<BooleanFormula> disjuncts = new ArrayList<>();
disjuncts.add(bmgr.and(x, y));
disjuncts.add(bmgr.and(z, w));
disjuncts.add(bmgr.and(u, v));
BooleanFormula f = bmgr.or(disjuncts);
BooleanFormula cnf = mgr.applyTactic(f, Tactic.TSEITIN_CNF);
assertThatFormula(cnf).isEquisatisfiableTo(f);
CNFChecker checker = new CNFChecker(mgr);
checker.visit(cnf);
assertThat(checker.isInCNF()).isTrue();
}
@Test
public void ufEliminationSimpleTest() throws SolverException, InterruptedException {
requireIntegers();
// f := uf(v1, v3) XOR uf(v2, v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula f = bmgr.xor(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4);
BooleanFormula withOutUfs = mgr.applyTactic(f, Tactic.ACKERMANNIZATION);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
assertThat(variablesAndUFs).doesNotContainKey("uf");
assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void ufEliminationNestedUfsTest() throws SolverException, InterruptedException {
requireIntegers();
// f :=uf2(uf1(v1, v2), v3) XOR uf2(uf1(v2, v1), v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
FunctionDeclaration<IntegerFormula> uf1Decl =
fmgr.declareUF("uf1", IntegerType, IntegerType, IntegerType);
Formula uf1a = fmgr.callUF(uf1Decl, variable1, variable2);
Formula uf1b = fmgr.callUF(uf1Decl, variable2, variable1);
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf2", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, uf1a, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, uf1b, variable4);
BooleanFormula f = bmgr.xor(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4);
BooleanFormula withOutUfs = mgr.applyTactic(f, Tactic.ACKERMANNIZATION);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
assertThat(variablesAndUFs).doesNotContainKey("uf1");
assertThat(variablesAndUFs).doesNotContainKey("uf2");
assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void ufEliminationNesteQuantifierTest() throws InterruptedException {
requireIntegers();
requireQuantifiers();
// f := exists v1,v2v,v3,v4 : uf(v1, v3) == uf(v2, v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula f =
qmgr.exists(
ImmutableList.of(variable1, variable2, variable3, variable4), bmgr.equivalence(f1, f2));
try {
mgr.applyTactic(f, Tactic.ACKERMANNIZATION);
assert_().fail();
} catch (IllegalArgumentException expected) {
}
}
private static class CNFChecker implements BooleanFormulaVisitor<Void> {
private final BooleanFormulaManager bfmgr;
boolean startsWithAnd = false;
boolean containsMoreAnd = false;
boolean started = false;
protected CNFChecker(FormulaManager pFmgr) {
bfmgr = pFmgr.getBooleanFormulaManager();
}
Void visit(BooleanFormula f) {
// TODO rewrite using RecursiveBooleanFormulaVisitor should make this class easier
return bfmgr.visit(f, this);
}
public boolean isInCNF() {
return (startsWithAnd && !containsMoreAnd) || (started && !startsWithAnd);
}
@Override
public Void visitConstant(boolean value) {
started = true;
return null;
}
@Override
public Void visitBoundVar(BooleanFormula f, int deBruijnIdx) {
started = true;
return null;
}
@Override
public Void visitAtom(BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) {
started = true;
return null;
}
@Override
public Void visitNot(BooleanFormula pOperand) {
started = true;
return visit(pOperand);
}
@Override
public Void visitAnd(List<BooleanFormula> pOperands) {
if (!started) {
started = true;
startsWithAnd = true;
} else {
containsMoreAnd = true;
}
pOperands.forEach(this::visit);
return null;
}
@Override
public Void visitOr(List<BooleanFormula> pOperands) {
if (started) {
pOperands.forEach(this::visit);
}
return null;
}
@Override
public Void visitXor(BooleanFormula operand1, BooleanFormula operand2) {
started = true;
return null;
}
@Override
public Void visitEquivalence(BooleanFormula pOperand1, BooleanFormula pOperand2) {
if (started) {
visit(pOperand1);
visit(pOperand2);
}
return null;
}
@Override
public Void visitImplication(BooleanFormula pOperand1, BooleanFormula pOperand2) {
if (started) {
visit(pOperand1);
visit(pOperand2);
}
return null;
}
@Override
public Void visitIfThenElse(
BooleanFormula pCondition, BooleanFormula pThenFormula, BooleanFormula pElseFormula) {
if (started) {
visit(pCondition);
visit(pThenFormula);
visit(pElseFormula);
}
return null;
}
@Override
public Void visitQuantifier(
Quantifier quantifier,
BooleanFormula quantifierAST,
List<Formula> boundVars,
BooleanFormula pBody) {
if (started) {
visit(pBody);
}
return null;
}
}
private static class NNFChecker implements BooleanFormulaVisitor<Void> {
private final BooleanFormulaManager bfmgr;
boolean wasLastVisitNot = false;
boolean notOnlyAtAtoms = true;
protected NNFChecker(FormulaManager pFmgr) {
bfmgr = pFmgr.getBooleanFormulaManager();
}
Void visit(BooleanFormula f) {
// TODO rewrite using RecursiveBooleanFormulaVisitor should make this class easier
return bfmgr.visit(f, this);
}
public boolean isInNNF() {
return notOnlyAtAtoms;
}
@Override
public Void visitConstant(boolean value) {
wasLastVisitNot = false;
return null;
}
@Override
public Void visitBoundVar(BooleanFormula var, int deBruijnIdx) {
wasLastVisitNot = false;
return null;
}
@Override
public Void visitAtom(BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) {
wasLastVisitNot = false;
return null;
}
@Override
public Void visitNot(BooleanFormula pOperand) {
wasLastVisitNot = true;
return visit(pOperand);
}
@Override
public Void visitAnd(List<BooleanFormula> pOperands) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
pOperands.forEach(this::visit);
}
return null;
}
@Override
public Void visitOr(List<BooleanFormula> pOperands) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
pOperands.forEach(this::visit);
}
return null;
}
@Override
public Void visitXor(BooleanFormula operand1, BooleanFormula operand2) {
return null;
}
@Override
public Void visitEquivalence(BooleanFormula pOperand1, BooleanFormula pOperand2) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
visit(pOperand1);
visit(pOperand2);
}
return null;
}
@Override
public Void visitImplication(BooleanFormula pOperand1, BooleanFormula pOperand2) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
visit(pOperand1);
visit(pOperand2);
}
return null;
}
@Override
public Void visitIfThenElse(
BooleanFormula pCondition, BooleanFormula pThenFormula, BooleanFormula pElseFormula) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
visit(pCondition);
visit(pThenFormula);
visit(pElseFormula);
}
return null;
}
@Override
public Void visitQuantifier(
Quantifier quantifier,
BooleanFormula quantifierAST,
List<Formula> boundVars,
BooleanFormula pBody) {
if (wasLastVisitNot) {
notOnlyAtAtoms = false;
} else {
visit(pBody);
}
return null;
}
}
}
| 15,243 | 32.283843 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverTheoriesTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.AssumptionViolatedException;
import org.junit.Ignore;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.BitvectorType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
@SuppressWarnings("LocalVariableName")
public class SolverTheoriesTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
@Test
public void basicBoolTest() throws SolverException, InterruptedException {
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeBoolean(false);
BooleanFormula c = bmgr.xor(a, b);
BooleanFormula d = bmgr.makeVariable("b");
BooleanFormula e = bmgr.xor(a, d);
BooleanFormula notImpl = bmgr.and(a, bmgr.not(e));
assertThatFormula(a).implies(c);
assertThatFormula(notImpl).isSatisfiable();
}
@Test
public void basicIntTest() {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
IntegerFormula b = imgr.makeVariable("b");
assertThat(a).isNotEqualTo(b);
}
@Test
public void basisRatTest() throws SolverException, InterruptedException {
requireRationals();
RationalFormula a = rmgr.makeVariable("int_c");
RationalFormula num = rmgr.makeNumber(4);
BooleanFormula f = rmgr.equal(rmgr.add(a, a), num);
assertThatFormula(f).isSatisfiable();
}
@Test
public void intTest1() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula num = imgr.makeNumber(2);
BooleanFormula f = imgr.equal(imgr.add(a, a), num);
assertThatFormula(f).isSatisfiable();
}
@Test
public void intTest2() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_b");
IntegerFormula num = imgr.makeNumber(1);
BooleanFormula f = imgr.equal(imgr.add(a, a), num);
assertThatFormula(f).isUnsatisfiable();
}
private void assertDivision(
IntegerFormula numerator,
IntegerFormula denumerator,
IntegerFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertDivision(true, numerator, denumerator, expectedResult, constraints);
}
private void assertDivision(
boolean includeNegation,
IntegerFormula numerator,
IntegerFormula denumerator,
IntegerFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertOperation(
includeNegation, buildDivision(numerator, denumerator, expectedResult), constraints);
}
private void assertDivision(
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertDivision(true, numerator, denumerator, signed, expectedResult, constraints);
}
private void assertDivision(
boolean includeNegation,
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertOperation(
includeNegation,
buildDivision(numerator, denumerator, signed, expectedResult),
constraints);
}
private void assertModulo(
IntegerFormula numerator,
IntegerFormula denumerator,
IntegerFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertModulo(true, numerator, denumerator, expectedResult, constraints);
}
private void assertModulo(
boolean includeNegation,
IntegerFormula numerator,
IntegerFormula denumerator,
IntegerFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertOperation(
includeNegation, buildModulo(numerator, denumerator, expectedResult), constraints);
}
private void assertModulo(
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertModulo(true, numerator, denumerator, signed, expectedResult, constraints);
}
private void assertModulo(
boolean includeNegation,
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult,
BooleanFormula... constraints)
throws SolverException, InterruptedException {
assertOperation(
includeNegation, buildModulo(numerator, denumerator, signed, expectedResult), constraints);
}
private BooleanFormula buildDivision(
IntegerFormula numerator, IntegerFormula denumerator, IntegerFormula expectedResult) {
return imgr.equal(imgr.divide(numerator, denumerator), expectedResult);
}
private BooleanFormula buildDivision(
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult) {
return bvmgr.equal(bvmgr.divide(numerator, denumerator, signed), expectedResult);
}
private BooleanFormula buildModulo(
IntegerFormula numerator, IntegerFormula denumerator, IntegerFormula expectedResult) {
return imgr.equal(imgr.modulo(numerator, denumerator), expectedResult);
}
private BooleanFormula buildModulo(
BitvectorFormula numerator,
BitvectorFormula denumerator,
boolean signed,
BitvectorFormula expectedResult) {
return bvmgr.equal(bvmgr.modulo(numerator, denumerator, signed), expectedResult);
}
private void assertOperation(
boolean includeNegation, BooleanFormula equation, BooleanFormula... constraints)
throws SolverException, InterruptedException {
// check positive case
assertThatFormula(bmgr.and(bmgr.and(constraints), equation)).isSatisfiable();
// check negative case
BooleanFormulaSubject negation =
assertThatFormula(bmgr.and(bmgr.and(constraints), bmgr.not(equation)));
if (includeNegation) {
negation.isUnsatisfiable();
} else {
negation.isSatisfiable();
}
}
@Test
public void intTest3_DivModLinear() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula b = imgr.makeVariable("int_b");
IntegerFormula num10 = imgr.makeNumber(10);
IntegerFormula num5 = imgr.makeNumber(5);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula num4 = imgr.makeNumber(4);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num0 = imgr.makeNumber(0);
IntegerFormula numNeg2 = imgr.makeNumber(-2);
IntegerFormula numNeg3 = imgr.makeNumber(-3);
IntegerFormula numNeg4 = imgr.makeNumber(-4);
IntegerFormula numNeg10 = imgr.makeNumber(-10);
BooleanFormula aEq10 = imgr.equal(a, num10);
BooleanFormula bEq2 = imgr.equal(b, num2);
BooleanFormula aEqNeg10 = imgr.equal(a, numNeg10);
BooleanFormula bEqNeg2 = imgr.equal(b, numNeg2);
assertDivision(num10, num5, num2);
assertDivision(num10, num3, num3);
assertDivision(numNeg10, num5, numNeg2);
assertDivision(numNeg10, numNeg2, num5);
assertDivision(num10, num5, num2);
assertDivision(num10, num3, num3);
assertDivision(num10, numNeg3, numNeg3);
assertDivision(num0, num3, num0);
assertDivision(a, num5, b, aEq10, bEq2);
assertDivision(a, num3, num3, aEq10);
assertDivision(a, num5, b, aEqNeg10, bEqNeg2);
assertDivision(a, num3, numNeg4, aEqNeg10);
assertDivision(a, numNeg3, num4, aEqNeg10);
switch (solverToUse()) {
case MATHSAT5: // modulo not supported
assertThrows(UnsupportedOperationException.class, () -> buildModulo(num10, num5, num0));
break;
default:
assertModulo(num10, num5, num0);
assertModulo(num10, num3, num1, aEq10);
assertModulo(numNeg10, num5, num0);
assertModulo(numNeg10, num3, num2);
assertModulo(numNeg10, numNeg3, num2);
assertModulo(a, num5, num0, aEq10);
assertModulo(a, num3, num1, aEq10);
assertModulo(a, num5, num0, aEqNeg10);
assertModulo(a, num3, num2, aEqNeg10);
assertModulo(a, numNeg3, num2, aEqNeg10);
}
}
@Test
public void intTest3_DivModLinear_zeroDenumerator() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula num10 = imgr.makeNumber(10);
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num0 = imgr.makeNumber(0);
BooleanFormula aEq10 = imgr.equal(a, num10);
// SMTLIB allows any value for division-by-zero.
switch (solverToUse()) {
case YICES2:
assertThrows(
IllegalArgumentException.class,
() -> assertThatFormula(buildDivision(num10, num0, num10)).isSatisfiable());
break;
default:
// division-by-zero results in an arbitrary result
assertDivision(false, num0, num0, num0);
assertDivision(false, num0, num0, num1);
assertDivision(false, num0, num0, num10);
assertDivision(false, num10, num0, num0);
assertDivision(false, num10, num0, num0);
assertDivision(false, num10, num0, num10);
assertDivision(false, a, num0, num0, aEq10);
assertDivision(false, a, num0, num1, aEq10);
assertDivision(false, a, num0, num10, aEq10);
}
switch (solverToUse()) {
case YICES2:
assertThrows(
IllegalArgumentException.class,
() -> assertThatFormula(buildModulo(num10, num0, num10)).isSatisfiable());
break;
case MATHSAT5: // modulo not supported
assertThrows(UnsupportedOperationException.class, () -> buildModulo(num10, num0, num10));
break;
default:
// modulo-by-zero results in an arbitrary result
assertModulo(false, num0, num0, num0);
assertModulo(false, num0, num0, num1);
assertModulo(false, num0, num0, num10);
assertModulo(false, num10, num0, num0);
assertModulo(false, num10, num0, num0);
assertModulo(false, num10, num0, num10);
assertModulo(false, a, num0, num0, aEq10);
assertModulo(false, a, num0, num1, aEq10);
assertModulo(false, a, num0, num10, aEq10);
}
}
@Test
public void intTest3_DivModNonLinear() throws SolverException, InterruptedException {
// not all solvers support division-by-variable,
// we guarantee soundness by allowing any value that yields SAT.
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula b = imgr.makeVariable("int_b");
IntegerFormula num10 = imgr.makeNumber(10);
IntegerFormula num5 = imgr.makeNumber(5);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num0 = imgr.makeNumber(0);
IntegerFormula numNeg2 = imgr.makeNumber(-2);
IntegerFormula numNeg10 = imgr.makeNumber(-10);
BooleanFormula aEq10 = imgr.equal(a, num10);
BooleanFormula bEq2 = imgr.equal(b, num2);
BooleanFormula bEqNeg2 = imgr.equal(b, numNeg2);
BooleanFormula aEqNeg10 = imgr.equal(a, numNeg10);
switch (solverToUse()) {
case SMTINTERPOL:
case YICES2:
assertThrows(UnsupportedOperationException.class, () -> buildDivision(a, b, num5));
assertThrows(UnsupportedOperationException.class, () -> buildModulo(a, b, num0));
break;
case MATHSAT5: // modulo not supported
assertDivision(a, b, num5, aEq10, bEq2);
assertDivision(a, b, num5, aEqNeg10, bEqNeg2);
assertThrows(UnsupportedOperationException.class, () -> buildModulo(num10, num5, num0));
break;
default:
assertDivision(a, b, num5, aEq10, bEq2);
assertDivision(a, b, num5, aEqNeg10, bEqNeg2);
assertModulo(a, b, num0, aEq10, bEq2);
assertModulo(a, b, num0, aEqNeg10, bEqNeg2);
}
// TODO negative case is disabled, because we would need the option
// solver.solver.useNonLinearIntegerArithmetic=true.
}
@Test
public void intTestBV_DivMod() throws SolverException, InterruptedException {
requireBitvectors();
final int bitsize = 8;
BitvectorFormula a = bvmgr.makeVariable(bitsize, "int_a");
BitvectorFormula b = bvmgr.makeVariable(bitsize, "int_b");
BitvectorFormula num253 = bvmgr.makeBitvector(bitsize, -3); // == 253 unsigned
BitvectorFormula num246 = bvmgr.makeBitvector(bitsize, -10); // == 246 unsigned
BitvectorFormula num82 = bvmgr.makeBitvector(bitsize, 82);
BitvectorFormula num49 = bvmgr.makeBitvector(bitsize, 49);
BitvectorFormula num10 = bvmgr.makeBitvector(bitsize, 10);
BitvectorFormula num5 = bvmgr.makeBitvector(bitsize, 5);
BitvectorFormula num3 = bvmgr.makeBitvector(bitsize, 3);
BitvectorFormula num2 = bvmgr.makeBitvector(bitsize, 2);
BitvectorFormula num1 = bvmgr.makeBitvector(bitsize, 1);
BitvectorFormula num0 = bvmgr.makeBitvector(bitsize, 0);
BitvectorFormula numNeg1 = bvmgr.makeBitvector(bitsize, -1);
BitvectorFormula numNeg2 = bvmgr.makeBitvector(bitsize, -2);
BitvectorFormula numNeg3 = bvmgr.makeBitvector(bitsize, -3);
BitvectorFormula numNeg10 = bvmgr.makeBitvector(bitsize, -10);
BooleanFormula aEq246 = bvmgr.equal(a, num246);
BooleanFormula aEq10 = bvmgr.equal(a, num10);
BooleanFormula bEq2 = bvmgr.equal(b, num2);
BooleanFormula bEq0 = bvmgr.equal(b, num0);
BooleanFormula aEqNeg10 = bvmgr.equal(a, numNeg10);
BooleanFormula bEq49 = bvmgr.equal(b, num49);
BooleanFormula bEq1 = bvmgr.equal(b, num1);
BooleanFormula bEqNeg1 = bvmgr.equal(b, numNeg1);
BooleanFormula bEqNeg2 = bvmgr.equal(b, numNeg2);
// positive numbers, signed.
assertDivision(a, num5, true, b, aEq10, bEq2);
assertDivision(a, num3, true, num3, aEq10);
assertDivision(a, numNeg3, true, numNeg3, aEq10);
assertDivision(a, b, true, num5, aEq10, bEq2);
assertModulo(a, num5, true, num0, aEq10);
assertModulo(a, num3, true, num1, aEq10);
assertModulo(a, numNeg3, true, num1, aEq10);
// positive numbers, unsigned.
assertDivision(a, num5, false, b, aEq10, bEq2);
assertDivision(a, num3, false, num3, aEq10);
assertDivision(a, num253, false, num0, aEq10);
assertDivision(a, b, false, num5, aEq10, bEq2);
assertModulo(a, num5, false, num0, aEq10);
assertModulo(a, num3, false, num1, aEq10);
assertModulo(a, num253, false, num10, aEq10);
// negative numbers, signed.
// bitvector-division for negative numbers is C99-conform!
assertDivision(a, num5, true, b, aEqNeg10, bEqNeg2);
assertDivision(a, num3, true, numNeg3, aEqNeg10);
assertDivision(a, numNeg3, true, num3, aEqNeg10);
assertDivision(a, b, true, num5, aEqNeg10, bEqNeg2);
assertModulo(a, num5, true, num0, aEqNeg10);
assertModulo(a, num3, true, numNeg1, aEqNeg10);
assertModulo(a, numNeg3, true, numNeg1, aEqNeg10);
// negative numbers, unsigned.
// bitvector-division for negative numbers is C99-conform!
assertDivision(a, num5, false, b, aEq246, bEq49);
assertDivision(a, num3, false, num82, aEq246);
assertDivision(a, num253, false, num0, aEq246);
assertDivision(a, b, false, num5, aEq246, bEq49);
assertModulo(a, num5, false, num1, aEq246);
assertModulo(a, num3, false, num0, aEq246);
assertModulo(a, num253, false, num246, aEq246);
// division by zero, signed.
assertDivision(a, num0, true, b, aEq10, bEqNeg1);
assertDivision(a, num0, true, b, aEqNeg10, bEq1);
assertDivision(a, b, true, numNeg1, aEq10, bEq0);
assertDivision(a, b, true, num1, aEqNeg10, bEq0);
assertModulo(a, num0, true, numNeg10, aEqNeg10);
// division by zero, unsigned.
assertDivision(a, num0, false, b, aEq10, bEqNeg1);
assertDivision(a, num0, false, b, aEqNeg10, bEqNeg1);
assertDivision(a, b, false, numNeg1, aEq10, bEq0);
assertDivision(a, b, false, numNeg1, aEqNeg10, bEq0);
assertModulo(a, num0, false, a, aEqNeg10);
}
@Test
public void intTest4_ModularCongruence_Simple() throws SolverException, InterruptedException {
requireIntegers();
final IntegerFormula x = imgr.makeVariable("x");
final BooleanFormula f1 = imgr.modularCongruence(x, imgr.makeNumber(0), 2);
final BooleanFormula f2 = imgr.equal(x, imgr.makeNumber(1));
assertThatFormula(bmgr.and(f1, f2)).isUnsatisfiable();
}
@Test
public void intTest4_ModularCongruence() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula b = imgr.makeVariable("int_b");
IntegerFormula c = imgr.makeVariable("int_c");
IntegerFormula d = imgr.makeVariable("int_d");
IntegerFormula num10 = imgr.makeNumber(10);
IntegerFormula num5 = imgr.makeNumber(5);
IntegerFormula num0 = imgr.makeNumber(0);
IntegerFormula numNeg5 = imgr.makeNumber(-5);
BooleanFormula fa = imgr.equal(a, num10);
BooleanFormula fb = imgr.equal(b, num5);
BooleanFormula fc = imgr.equal(c, num0);
BooleanFormula fd = imgr.equal(d, numNeg5);
// we have equal results modulo 5
BooleanFormula fConb5 = imgr.modularCongruence(a, b, 5);
BooleanFormula fConc5 = imgr.modularCongruence(a, c, 5);
BooleanFormula fCond5 = imgr.modularCongruence(a, d, 5);
// we have different results modulo 7
BooleanFormula fConb7 = imgr.modularCongruence(a, b, 7);
BooleanFormula fConc7 = imgr.modularCongruence(a, c, 7);
BooleanFormula fCond7 = imgr.modularCongruence(a, d, 7);
// check modular congruence, a=10 && b=5 && (a mod 5 = b mod 5)
assertThatFormula(bmgr.and(fa, fb, fConb5)).isSatisfiable();
assertThatFormula(bmgr.and(fa, fb, bmgr.not(fConb5))).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fc, fConc5)).isSatisfiable();
assertThatFormula(bmgr.and(fa, fc, bmgr.not(fConc5))).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fd, fCond5)).isSatisfiable();
assertThatFormula(bmgr.and(fa, fd, bmgr.not(fCond5))).isUnsatisfiable();
// check modular congruence, a=10 && b=5 && (a mod 7 != b mod 7)
assertThatFormula(bmgr.and(fa, fb, fConb7)).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fb, bmgr.not(fConb7))).isSatisfiable();
assertThatFormula(bmgr.and(fa, fc, fConc7)).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fc, bmgr.not(fConc7))).isSatisfiable();
assertThatFormula(bmgr.and(fa, fd, fCond7)).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fd, bmgr.not(fCond7))).isSatisfiable();
}
@Test
public void intTest4_ModularCongruence_NegativeNumbers()
throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("int_a");
IntegerFormula b = imgr.makeVariable("int_b");
IntegerFormula c = imgr.makeVariable("int_c");
IntegerFormula num8 = imgr.makeNumber(8);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula numNeg2 = imgr.makeNumber(-2);
BooleanFormula fa = imgr.equal(a, num8);
BooleanFormula fb = imgr.equal(b, num3);
BooleanFormula fc = imgr.equal(c, numNeg2);
BooleanFormula fConb = imgr.modularCongruence(a, b, 5);
BooleanFormula fConc = imgr.modularCongruence(a, c, 5);
// check modular congruence, a=10 && b=5 && (a mod 5 = b mod 5)
assertThatFormula(bmgr.and(fa, fb, fConb)).isSatisfiable();
assertThatFormula(bmgr.and(fa, fb, bmgr.not(fConb))).isUnsatisfiable();
assertThatFormula(bmgr.and(fa, fc, fConc)).isSatisfiable();
assertThatFormula(bmgr.and(fa, fc, bmgr.not(fConc))).isUnsatisfiable();
}
@Test
public void testHardCongruence() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula a = imgr.makeVariable("a");
IntegerFormula b = imgr.makeVariable("b");
IntegerFormula c = imgr.makeVariable("c");
List<BooleanFormula> constraints = new ArrayList<>();
Random r = new Random(42);
int bitSize = 7; // difficulty
BigInteger prime1 = BigInteger.probablePrime(bitSize, r);
BigInteger prime2 = BigInteger.probablePrime(bitSize + 1, r);
BigInteger prime3 = BigInteger.probablePrime(bitSize + 2, r);
constraints.add(imgr.modularCongruence(imgr.add(a, imgr.makeNumber(1)), b, prime1));
constraints.add(imgr.modularCongruence(b, c, prime2));
constraints.add(imgr.modularCongruence(a, c, prime3));
try (ProverEnvironment pe = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
pe.addConstraint(imgr.greaterThan(a, imgr.makeNumber(1)));
pe.addConstraint(imgr.greaterThan(b, imgr.makeNumber(1)));
pe.addConstraint(imgr.greaterThan(c, imgr.makeNumber(1)));
pe.addConstraint(bmgr.and(constraints));
assertThat(pe.isUnsat()).isFalse();
try (Model m = pe.getModel()) {
BigInteger aValue = m.evaluate(a);
BigInteger bValue = m.evaluate(b);
BigInteger cValue = m.evaluate(c);
assertThat(aValue.add(BigInteger.ONE).subtract(bValue).mod(prime1))
.isEqualTo(BigInteger.ZERO);
assertThat(bValue.subtract(cValue).mod(prime2)).isEqualTo(BigInteger.ZERO);
assertThat(aValue.subtract(cValue).mod(prime3)).isEqualTo(BigInteger.ZERO);
}
}
}
@Test
public void realTest() throws SolverException, InterruptedException {
requireRationals();
RationalFormula a = rmgr.makeVariable("int_c");
RationalFormula num = rmgr.makeNumber(1);
BooleanFormula f = rmgr.equal(rmgr.add(a, a), num);
assertThatFormula(f).isSatisfiable();
}
@Test
public void test_BitvectorIsZeroAfterShiftLeft() throws SolverException, InterruptedException {
requireBitvectors();
BitvectorFormula one = bvmgr.makeBitvector(32, 1);
// unsigned char
BitvectorFormula a = bvmgr.makeVariable(8, "char_a");
BitvectorFormula b = bvmgr.makeVariable(8, "char_b");
BitvectorFormula rightOp = bvmgr.makeBitvector(32, 7);
// 'cast' a to unsigned int
a = bvmgr.extend(a, 32 - 8, false);
b = bvmgr.extend(b, 32 - 8, false);
a = bvmgr.or(a, one);
b = bvmgr.or(b, one);
a = bvmgr.extract(a, 7, 0);
b = bvmgr.extract(b, 7, 0);
a = bvmgr.extend(a, 32 - 8, false);
b = bvmgr.extend(b, 32 - 8, false);
a = bvmgr.shiftLeft(a, rightOp);
b = bvmgr.shiftLeft(b, rightOp);
a = bvmgr.extract(a, 7, 0);
b = bvmgr.extract(b, 7, 0);
BooleanFormula f = bmgr.not(bvmgr.equal(a, b));
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testUfWithBoolType() throws SolverException, InterruptedException {
requireIntegers();
FunctionDeclaration<BooleanFormula> uf =
fmgr.declareUF("fun_ib", FormulaType.BooleanType, FormulaType.IntegerType);
BooleanFormula uf0 = fmgr.callUF(uf, imgr.makeNumber(0));
BooleanFormula uf1 = fmgr.callUF(uf, imgr.makeNumber(1));
BooleanFormula uf2 = fmgr.callUF(uf, imgr.makeNumber(2));
BooleanFormula f01 = bmgr.xor(uf0, uf1);
BooleanFormula f02 = bmgr.xor(uf0, uf2);
BooleanFormula f12 = bmgr.xor(uf1, uf2);
assertThatFormula(f01).isSatisfiable();
assertThatFormula(f02).isSatisfiable();
assertThatFormula(f12).isSatisfiable();
BooleanFormula f = bmgr.and(f01, f02, f12);
assertThatFormula(f).isUnsatisfiable();
}
@Test
public void testUfWithBoolArg() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support boolean arguments", solverToUse())
.that(solver)
.isNotEqualTo(Solvers.MATHSAT5);
requireIntegers();
FunctionDeclaration<IntegerFormula> uf =
fmgr.declareUF("fun_bi", FormulaType.IntegerType, FormulaType.BooleanType);
IntegerFormula ufTrue = fmgr.callUF(uf, bmgr.makeBoolean(true));
IntegerFormula ufFalse = fmgr.callUF(uf, bmgr.makeBoolean(false));
BooleanFormula f = bmgr.not(imgr.equal(ufTrue, ufFalse));
assertThatFormula(f).isSatisfiable();
}
@Test
public void quantifierEliminationTest1() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula var_B = imgr.makeVariable("b");
IntegerFormula var_C = imgr.makeVariable("c");
IntegerFormula num_2 = imgr.makeNumber(2);
IntegerFormula num_1000 = imgr.makeNumber(1000);
BooleanFormula eq_c_2 = imgr.equal(var_C, num_2);
IntegerFormula minus_b_c = imgr.subtract(var_B, var_C);
BooleanFormula gt_bMinusC_1000 = imgr.greaterThan(minus_b_c, num_1000);
BooleanFormula and_cEq2_bMinusCgt1000 = bmgr.and(eq_c_2, gt_bMinusC_1000);
BooleanFormula f = qmgr.exists(ImmutableList.of(var_C), and_cEq2_bMinusCgt1000);
BooleanFormula result = qmgr.eliminateQuantifiers(f);
assertThat(result.toString()).doesNotContain("exists");
assertThat(result.toString()).doesNotContain("c");
BooleanFormula expected = imgr.greaterOrEquals(var_B, imgr.makeNumber(1003));
assertThatFormula(result).isEquivalentTo(expected);
}
@Test
@Ignore
public void quantifierEliminationTest2() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula i1 = imgr.makeVariable("i@1");
IntegerFormula j1 = imgr.makeVariable("j@1");
IntegerFormula j2 = imgr.makeVariable("j@2");
IntegerFormula a1 = imgr.makeVariable("a@1");
IntegerFormula _1 = imgr.makeNumber(1);
IntegerFormula _minus1 = imgr.makeNumber(-1);
IntegerFormula _1_plus_a1 = imgr.add(_1, a1);
BooleanFormula not_j1_eq_minus1 = bmgr.not(imgr.equal(j1, _minus1));
BooleanFormula i1_eq_1_plus_a1 = imgr.equal(i1, _1_plus_a1);
IntegerFormula j2_plus_a1 = imgr.add(j2, a1);
BooleanFormula j1_eq_j2_plus_a1 = imgr.equal(j1, j2_plus_a1);
BooleanFormula fm = bmgr.and(i1_eq_1_plus_a1, not_j1_eq_minus1, j1_eq_j2_plus_a1);
BooleanFormula q = qmgr.exists(ImmutableList.of(j1), fm);
BooleanFormula result = qmgr.eliminateQuantifiers(q);
assertThat(result.toString()).doesNotContain("exists");
assertThat(result.toString()).doesNotContain("j@1");
BooleanFormula expected = bmgr.not(imgr.equal(i1, j2));
assertThatFormula(result).isEquivalentTo(expected);
}
@Test
public void testGetFormulaType() {
requireIntegers();
BooleanFormula _boolVar = bmgr.makeVariable("boolVar");
assertThat(mgr.getFormulaType(_boolVar)).isEqualTo(FormulaType.BooleanType);
IntegerFormula _intVar = imgr.makeNumber(1);
assertThat(mgr.getFormulaType(_intVar)).isEqualTo(FormulaType.IntegerType);
requireArrays();
ArrayFormula<IntegerFormula, IntegerFormula> _arrayVar =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
assertThat(mgr.getFormulaType(_arrayVar)).isInstanceOf(FormulaType.ArrayFormulaType.class);
}
@Test
public void testMakeIntArray() {
requireArrays();
requireIntegers();
IntegerFormula _i = imgr.makeVariable("i");
IntegerFormula _1 = imgr.makeNumber(1);
IntegerFormula _i_plus_1 = imgr.add(_i, _1);
ArrayFormula<IntegerFormula, IntegerFormula> _b =
amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType);
IntegerFormula _b_at_i_plus_1 = amgr.select(_b, _i_plus_1);
switch (solver) {
case MATHSAT5:
// Mathsat5 has a different internal representation of the formula
assertThat(_b_at_i_plus_1.toString()).isEqualTo("(`read_int_int` b (`+_int` i 1))");
break;
case PRINCESS:
assertThat(_b_at_i_plus_1.toString()).isEqualTo("select(b, (i + 1))");
break;
default:
assertThat(_b_at_i_plus_1.toString())
.isEqualTo("(select b (+ i 1))"); // Compatibility to all solvers not guaranteed
}
}
@Test
public void testMakeBitVectorArray() {
requireArrays();
requireBitvectors();
assume()
.withMessage("Solver does not support bit-vector arrays.")
.that(solver)
.isNotEqualTo(Solvers.PRINCESS);
BitvectorFormula _i = mgr.getBitvectorFormulaManager().makeVariable(64, "i");
ArrayFormula<BitvectorFormula, BitvectorFormula> _b =
amgr.makeArray(
"b",
FormulaType.getBitvectorTypeWithSize(64),
FormulaType.getBitvectorTypeWithSize(32));
BitvectorFormula _b_at_i = amgr.select(_b, _i);
switch (solver) {
case MATHSAT5:
// Mathsat5 has a different internal representation of the formula
assertThat(_b_at_i.toString()).isEqualTo("(`read_T(18)_T(20)` b i)");
break;
case BOOLECTOR:
assume()
.withMessage("Solver %s does not printing formulae.", solverToUse())
.that(solver)
.isNotEqualTo(Solvers.BOOLECTOR);
break;
default:
assertThat(_b_at_i.toString())
.isEqualTo("(select b i)"); // Compatibility to all solvers not guaranteed
}
}
@Test
public void testNestedRationalArray() {
requireArrays();
requireRationals();
requireIntegers();
IntegerFormula _i = imgr.makeVariable("i");
ArrayFormula<IntegerFormula, ArrayFormula<IntegerFormula, RationalFormula>> multi =
amgr.makeArray(
"multi",
FormulaType.IntegerType,
FormulaType.getArrayType(FormulaType.IntegerType, FormulaType.RationalType));
RationalFormula valueInMulti = amgr.select(amgr.select(multi, _i), _i);
switch (solver) {
case MATHSAT5:
assertThat(valueInMulti.toString())
.isEqualTo("(`read_int_rat` (`read_int_T(17)` multi i) i)");
break;
default:
assertThat(valueInMulti.toString()).isEqualTo("(select (select multi i) i)");
}
}
@Test
public void testNestedBitVectorArray() {
requireArrays();
requireBitvectors();
requireIntegers();
assume()
.withMessage("Solver does not support bit-vector arrays.")
.that(solver)
.isNotEqualTo(Solvers.PRINCESS);
IntegerFormula _i = imgr.makeVariable("i");
ArrayFormula<IntegerFormula, ArrayFormula<IntegerFormula, BitvectorFormula>> multi =
amgr.makeArray(
"multi",
FormulaType.IntegerType,
FormulaType.getArrayType(
FormulaType.IntegerType, FormulaType.getBitvectorTypeWithSize(32)));
BitvectorFormula valueInMulti = amgr.select(amgr.select(multi, _i), _i);
switch (solver) {
case MATHSAT5:
String readWrite = "(`read_int_T(18)` (`read_int_T(19)` multi i) i)";
assertThat(valueInMulti.toString()).isEqualTo(readWrite);
break;
default:
assertThat(valueInMulti.toString()).isEqualTo("(select (select multi i) i)");
}
}
@Test
public void nonLinearMultiplication() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i2 = imgr.makeNumber(2);
IntegerFormula i3 = imgr.makeNumber(3);
IntegerFormula i4 = imgr.makeNumber(4);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
IntegerFormula x_mult_y;
try {
x_mult_y = imgr.multiply(x, y);
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
BooleanFormula x_equal_2 = imgr.equal(i2, x);
BooleanFormula y_equal_3 = imgr.equal(i3, y);
BooleanFormula z_equal_4 = imgr.equal(i4, z);
BooleanFormula z_equal_x_mult_y = imgr.equal(z, x_mult_y);
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(x_equal_2);
env.push(y_equal_3);
env.push(z_equal_4);
env.push(z_equal_x_mult_y);
assertThat(env).isUnsatisfiable();
}
}
@Test
public void composedLinearMultiplication() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i2 = imgr.makeNumber(2);
IntegerFormula i3 = imgr.makeNumber(3);
IntegerFormula i4 = imgr.makeNumber(4);
IntegerFormula x = imgr.makeVariable("x");
// MULT should be supported by all solvers, DIV/MOD are missing in Mathsat.
IntegerFormula mult = imgr.multiply(x, imgr.add(i2, imgr.add(i3, i4)));
IntegerFormula div;
IntegerFormula mod;
try {
div = imgr.divide(x, imgr.add(i2, imgr.add(i3, i4)));
mod = imgr.modulo(x, imgr.add(i2, imgr.add(i3, i4)));
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(imgr.greaterThan(mult, i4));
env.push(imgr.greaterThan(div, i4));
env.push(imgr.greaterThan(mod, i2));
assertThat(env).isSatisfiable();
}
}
@Test
public void multiplicationSquares() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i2 = imgr.makeNumber(2);
IntegerFormula i3 = imgr.makeNumber(3);
IntegerFormula i4 = imgr.makeNumber(4);
IntegerFormula i5 = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
IntegerFormula xx;
IntegerFormula yy;
IntegerFormula zz;
try {
xx = imgr.multiply(x, x);
yy = imgr.multiply(y, y);
zz = imgr.multiply(z, z);
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
try (ProverEnvironment env = context.newProverEnvironment()) {
// check x*x + y*y = z*z
env.push(imgr.equal(zz, imgr.add(xx, yy)));
{
// SAT with x=4 and y=3
env.push(imgr.equal(x, i3));
env.push(imgr.equal(y, i4));
assertThat(env).isSatisfiable();
env.pop();
env.pop();
}
{ // SAT with z=5
env.push(imgr.equal(z, i5));
assertThat(env).isSatisfiable();
env.pop();
}
{
// UNSAT with z=5 and x=2
env.push(imgr.equal(z, i5));
env.push(imgr.equal(x, i2));
assertThat(env).isUnsatisfiable();
env.pop();
env.pop();
}
{ // UNSAT with z=5 and x>3 and y>3
env.push(imgr.equal(z, i5));
env.push(imgr.greaterThan(x, i3));
env.push(imgr.greaterThan(y, i3));
assertThat(env).isUnsatisfiable();
env.pop();
env.pop();
env.pop();
}
}
}
@Test
public void multiplicationFactors() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i37 = imgr.makeNumber(37);
IntegerFormula i1 = imgr.makeNumber(1);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula x_mult_y;
try {
x_mult_y = imgr.multiply(x, y);
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(imgr.equal(x_mult_y, i37));
assertThat(env).isSatisfiable();
env.push(imgr.greaterThan(x, i1));
env.push(imgr.greaterThan(y, i1));
assertThat(env).isUnsatisfiable();
}
}
@Test
public void multiplicationCubic() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i125 = imgr.makeNumber(125);
IntegerFormula i27 = imgr.makeNumber(27);
IntegerFormula i5 = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula xxx;
IntegerFormula yyy;
try {
xxx = imgr.multiply(x, imgr.multiply(x, x));
yyy = imgr.multiply(y, imgr.multiply(y, y));
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(imgr.equal(xxx, i125));
env.push(imgr.equal(yyy, i27));
assertThat(env).isSatisfiable();
env.push(imgr.lessThan(x, i5));
assertThat(env).isUnsatisfiable();
}
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(imgr.equal(imgr.add(xxx, yyy), imgr.add(i27, i125)));
env.push(imgr.lessThan(y, i5));
env.push(imgr.equal(x, i5));
assertThat(env).isSatisfiable();
env.pop();
env.push(imgr.lessThan(x, i5));
assertThat(env).isUnsatisfiable();
}
}
@Test
public void nonLinearDivision() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula i2 = imgr.makeNumber(2);
IntegerFormula i3 = imgr.makeNumber(3);
IntegerFormula i4 = imgr.makeNumber(4);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
IntegerFormula x_div_y;
try {
x_div_y = imgr.divide(x, y);
} catch (UnsupportedOperationException e) {
// do nothing, this exception is fine here, because solvers do not need
// to support non-linear arithmetic, we can then skip the test completely
throw new AssumptionViolatedException("Support for non-linear arithmetic is optional", e);
}
BooleanFormula x_equal_4 = imgr.equal(i4, x);
BooleanFormula y_equal_2 = imgr.equal(i2, y);
BooleanFormula z_equal_3 = imgr.equal(i3, z);
BooleanFormula z_equal_x_div_y = imgr.equal(z, x_div_y);
try (ProverEnvironment env = context.newProverEnvironment()) {
env.push(x_equal_4);
env.push(y_equal_2);
env.push(z_equal_3);
env.push(z_equal_x_div_y);
assertThat(env).isUnsatisfiable();
}
}
@Test
public void integerDivisionRounding() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula varSeven = imgr.makeVariable("a");
IntegerFormula varEight = imgr.makeVariable("b");
IntegerFormula two = imgr.makeNumber(2);
IntegerFormula three = imgr.makeNumber(3);
// Test that 8/3 and 7/3 are rounded as expected for all combinations of positive/negative
// numbers
BooleanFormula f =
bmgr.and(
imgr.equal(varSeven, imgr.makeNumber(7)),
imgr.equal(varEight, imgr.makeNumber(8)),
imgr.equal(imgr.divide(varSeven, three), two),
imgr.equal(imgr.divide(imgr.negate(varSeven), three), imgr.negate(three)),
imgr.equal(imgr.divide(varSeven, imgr.negate(three)), imgr.negate(two)),
imgr.equal(imgr.divide(imgr.negate(varSeven), imgr.negate(three)), three),
imgr.equal(imgr.divide(varEight, three), two),
imgr.equal(imgr.divide(imgr.negate(varEight), three), imgr.negate(three)),
imgr.equal(imgr.divide(varEight, imgr.negate(three)), imgr.negate(two)),
imgr.equal(imgr.divide(imgr.negate(varEight), imgr.negate(three)), three));
assertThatFormula(f).isSatisfiable();
}
@Test
public void bvInRange() throws SolverException, InterruptedException {
requireBitvectors();
assertThatFormula(
bvmgr.equal(
bvmgr.add(bvmgr.makeBitvector(4, 15), bvmgr.makeBitvector(4, -8)),
bvmgr.makeBitvector(4, 7)))
.isTautological();
}
@Test
@SuppressWarnings("CheckReturnValue")
public void bvOutOfRange() {
requireBitvectors();
for (int[] sizeAndValue : new int[][] {{4, 32}, {4, -9}, {8, 300}, {8, -160}}) {
try {
bvmgr.makeBitvector(sizeAndValue[0], sizeAndValue[1]);
assert_().fail();
} catch (IllegalArgumentException expected) {
}
}
for (int size : new int[] {4, 6, 8, 10, 16, 32}) {
// allowed values
bvmgr.makeBitvector(size, (1L << size) - 1);
bvmgr.makeBitvector(size, -(1L << (size - 1)));
// forbitten values
try {
bvmgr.makeBitvector(size, 1L << size);
assert_().fail();
} catch (IllegalArgumentException expected) {
}
try {
bvmgr.makeBitvector(size, -(1L << (size - 1)) - 1);
assert_().fail();
} catch (IllegalArgumentException expected) {
}
}
for (int size : new int[] {36, 40, 64, 65, 100, 128, 200, 250, 1000, 10000}) {
if (size > 64) {
assume()
.withMessage("Solver does not support large bitvectors")
.that(solverToUse())
.isNotEqualTo(Solvers.CVC4);
}
// allowed values
bvmgr.makeBitvector(size, BigInteger.ONE.shiftLeft(size).subtract(BigInteger.ONE));
bvmgr.makeBitvector(size, BigInteger.ONE.shiftLeft(size - 1).negate());
// forbitten values
try {
bvmgr.makeBitvector(size, BigInteger.ONE.shiftLeft(size));
assert_().fail();
} catch (IllegalArgumentException expected) {
}
try {
bvmgr.makeBitvector(
size, BigInteger.ONE.shiftLeft(size - 1).negate().subtract(BigInteger.ONE));
assert_().fail();
} catch (IllegalArgumentException expected) {
}
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void bvITETest() {
requireBitvectors();
BitvectorType bv8 = FormulaType.getBitvectorTypeWithSize(8);
BitvectorFormula x = bvmgr.makeVariable(bv8, "x");
bmgr.ifThenElse(bmgr.makeBoolean(true), x, x);
}
private static final ImmutableSet<Solvers> VAR_TRACKING_SOLVERS =
ImmutableSet.of(
Solvers.SMTINTERPOL,
Solvers.MATHSAT5,
Solvers.CVC4,
Solvers.BOOLECTOR,
Solvers.YICES2,
Solvers.CVC5);
private static final ImmutableSet<Solvers> VAR_AND_UF_TRACKING_SOLVERS =
ImmutableSet.of(Solvers.SMTINTERPOL, Solvers.MATHSAT5, Solvers.BOOLECTOR, Solvers.YICES2);
@Test
@SuppressWarnings("CheckReturnValue")
public void testVariableWithDifferentSort() {
assume().that(solverToUse()).isNotIn(VAR_TRACKING_SOLVERS);
bmgr.makeVariable("x");
if (imgr != null) {
imgr.makeVariable("x");
} else if (bvmgr != null) {
bvmgr.makeVariable(8, "x");
}
}
@Test(expected = Exception.class) // complement of above test case
@SuppressWarnings("CheckReturnValue")
public void testFailOnVariableWithDifferentSort() {
assume().that(solverToUse()).isIn(VAR_TRACKING_SOLVERS);
bmgr.makeVariable("x");
if (imgr != null) {
imgr.makeVariable("x");
} else if (bvmgr != null) {
bvmgr.makeVariable(8, "x");
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void testVariableAndUFWithDifferentSort() {
assume().that(solverToUse()).isNotIn(VAR_AND_UF_TRACKING_SOLVERS);
bmgr.makeVariable("y");
fmgr.declareUF("y", FormulaType.BooleanType, FormulaType.BooleanType);
}
@Test(expected = Exception.class) // complement of above test case
@SuppressWarnings("CheckReturnValue")
public void testFailOnVariableAndUFWithDifferentSort() {
assume().that(solverToUse()).isIn(VAR_AND_UF_TRACKING_SOLVERS);
bmgr.makeVariable("y");
fmgr.declareUF("y", FormulaType.BooleanType, FormulaType.BooleanType);
}
@Test(expected = Exception.class) // different ordering of above test case
@SuppressWarnings("CheckReturnValue")
public void testFailOnUFAndVariableWithDifferentSort() {
assume().that(solverToUse()).isIn(VAR_AND_UF_TRACKING_SOLVERS);
fmgr.declareUF("y", FormulaType.BooleanType, FormulaType.BooleanType);
bmgr.makeVariable("y");
}
@Test
public void testVariableAndUFWithEqualSort() {
assume()
.withMessage("Solver %s does not support UFs without arguments", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.BOOLECTOR, Solvers.CVC5);
BooleanFormula z1 = bmgr.makeVariable("z");
BooleanFormula z2 = fmgr.declareAndCallUF("z", FormulaType.BooleanType);
if (ImmutableSet.of(Solvers.CVC4, Solvers.PRINCESS).contains(solverToUse())) {
assertThat(z1).isNotEqualTo(z2);
} else {
assertThat(z1).isEqualTo(z2);
}
}
}
| 46,416 | 36.193109 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/SolverVisitorTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.Truth;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.BitvectorType;
import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor;
import org.sosy_lab.java_smt.api.visitors.BooleanFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.DefaultBooleanFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.FormulaTransformationVisitor;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
public class SolverVisitorTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
/** visit a formula and fail on OTHER, i.e., unexpected function declaration type. */
private final class FunctionDeclarationVisitorNoOther extends DefaultFormulaVisitor<Formula> {
private final List<FunctionDeclarationKind> found = new ArrayList<>();
@Override
public Formula visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
found.add(functionDeclaration.getKind());
Truth.assert_()
.withMessage(
"unexpected declaration kind '%s' in function '%s' with args '%s'.",
functionDeclaration, f, args)
.that(functionDeclaration.getKind())
.isNotEqualTo(FunctionDeclarationKind.OTHER);
for (Formula arg : args) {
mgr.visit(arg, this);
}
return visitDefault(f);
}
@Override
protected Formula visitDefault(Formula pF) {
return pF;
}
}
/** visit a formula and fail on UF, i.e., uninterpreted function declaration type. */
private final class FunctionDeclarationVisitorNoUF extends DefaultFormulaVisitor<Formula> {
private final List<FunctionDeclarationKind> found = new ArrayList<>();
@Override
public Formula visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
found.add(functionDeclaration.getKind());
Truth.assert_()
.withMessage(
"uninterpreted function declaration '%s' in function '%s' with args '%s'.",
functionDeclaration, f, args)
.that(functionDeclaration.getKind())
.isNotEqualTo(FunctionDeclarationKind.UF);
for (Formula arg : args) {
mgr.visit(arg, this);
}
return visitDefault(f);
}
@Override
protected Formula visitDefault(Formula pF) {
return pF;
}
}
/** visit only constants and ignore other operations. */
private static final class ConstantsVisitor extends DefaultFormulaVisitor<Formula> {
private final List<Object> found = new ArrayList<>();
@Override
public Formula visitConstant(Formula f, Object value) {
found.add(value);
return visitDefault(f);
}
@Override
protected Formula visitDefault(Formula pF) {
return pF;
}
}
@Before
public void setup() {
requireVisitor();
}
@Test
public void booleanIdVisit() {
BooleanFormula t = bmgr.makeBoolean(true);
BooleanFormula f = bmgr.makeBoolean(false);
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula y = bmgr.makeVariable("y");
BooleanFormula z = bmgr.makeVariable("z");
BooleanFormula and = bmgr.and(x, y);
BooleanFormula or = bmgr.or(x, y);
BooleanFormula ite = bmgr.ifThenElse(x, and, or);
BooleanFormula impl = bmgr.implication(z, y);
BooleanFormula eq = bmgr.equivalence(t, y);
BooleanFormula not = bmgr.not(eq);
for (BooleanFormula bf : ImmutableList.of(t, f, x, y, z, and, or, ite, impl, eq, not)) {
BooleanFormulaVisitor<BooleanFormula> identityVisitor =
new BooleanFormulaTransformationVisitor(mgr) {
// we need a subclass, because the original class is 'abstract'
};
assertThatFormula(bmgr.visit(bf, identityVisitor)).isEqualTo(bf);
}
}
@Test
public void bitvectorIdVisit() throws SolverException, InterruptedException {
requireBitvectors();
BitvectorType bv8 = FormulaType.getBitvectorTypeWithSize(8);
BitvectorFormula x = bvmgr.makeVariable(bv8, "x");
BitvectorFormula y1 = bvmgr.makeVariable(bv8, "y");
BitvectorFormula y2 = bvmgr.add(y1, bvmgr.makeBitvector(8, 13));
BitvectorFormula y3 = bvmgr.makeBitvector(8, 13);
for (BitvectorFormula y : new BitvectorFormula[] {y1, y2, y3}) {
for (BooleanFormula f :
ImmutableList.of(
bvmgr.equal(x, y),
bmgr.not(bvmgr.equal(x, y)),
bvmgr.lessThan(x, y, true),
bvmgr.lessThan(x, y, false),
bvmgr.lessOrEquals(x, y, true),
bvmgr.lessOrEquals(x, y, false),
bvmgr.greaterThan(x, y, true),
bvmgr.greaterThan(x, y, false),
bvmgr.greaterOrEquals(x, y, true),
bvmgr.greaterOrEquals(x, y, false))) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
if (Solvers.PRINCESS != solver) {
// Princess models BV theory with intervals, such as "mod_cast(lower, upper , value)".
// The interval function is of FunctionDeclarationKind.OTHER and thus we cannot check it.
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
}
BooleanFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(f).isEquivalentTo(f2);
}
for (BitvectorFormula f :
ImmutableList.of(
bvmgr.add(x, y),
bvmgr.subtract(x, y),
bvmgr.multiply(x, y),
bvmgr.and(x, y),
bvmgr.or(x, y),
bvmgr.xor(x, y),
bvmgr.divide(x, y, true),
bvmgr.divide(x, y, false),
bvmgr.modulo(x, y, true),
bvmgr.modulo(x, y, false),
bvmgr.not(x),
bvmgr.negate(x),
bvmgr.extract(x, 7, 5),
bvmgr.extract(x, 7, 5),
bvmgr.concat(x, y))) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
if (Solvers.PRINCESS != solver) {
// Princess models BV theory with intervals, such as "mod_cast(lower, upper , value)".
// The interval function is of FunctionDeclarationKind.OTHER and thus we cannot check it.
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
}
BitvectorFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(bmgr.not(bvmgr.equal(f, f2))).isUnsatisfiable();
}
}
}
@Test
public void bitvectorIdVisit2() throws SolverException, InterruptedException {
requireBitvectors();
BitvectorFormula n = bvmgr.makeBitvector(8, 13);
for (BitvectorFormula f : new BitvectorFormula[] {n}) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
if (Solvers.PRINCESS != solver) {
// Princess models BV theory with intervals, such as "mod_cast(lower, upper , value)".
// The interval function is of FunctionDeclarationKind.OTHER and thus we cannot check it.
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
}
BitvectorFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(bmgr.not(bvmgr.equal(f, f2))).isUnsatisfiable();
}
}
@Test
public void integerConstantVisit() {
requireIntegers();
for (long n :
new long[] {
0, 1, 2, 17, 127, 255, -1, -2, -17, -127, 127000, 255000, -100, -200, -1700, -127000,
-255000,
}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(imgr.makeNumber(n), visitor);
assertThat(visitor.found).containsExactly(BigInteger.valueOf(n));
}
}
@Test
public void rationalConstantVisit() {
requireRationals();
for (long n :
new long[] {
0, 1, 2, 17, 127, 255, -1, -2, -17, -127, 127000, 255000, -100, -200, -1700, -127000,
-255000,
}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(rmgr.makeNumber(n), visitor); // normal integers as rationals
assertThat(visitor.found).containsExactly(BigInteger.valueOf(n));
}
for (long n :
new long[] {
1, 2, 17, 127, 255, -1, -2, -17, -127, 127000, 255000, -100, -200, -1700, -127000,
-255000,
}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(rmgr.makeNumber(Rational.ofLongs(n, 321)), visitor);
assertThat(visitor.found).containsExactly(Rational.ofLongs(n, 321));
}
}
@Test
public void bitvectorConstantVisit() {
requireBitvectors();
// check small bitsize
for (long n : new long[] {0, 1, 2, 17, 99, 127, 255}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(bvmgr.makeBitvector(8, n), visitor);
assertThat(visitor.found).containsExactly(BigInteger.valueOf(n));
}
for (long n : new long[] {-1, -2, -17, -99, -127}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(bvmgr.makeBitvector(8, n), visitor);
assertThat(visitor.found)
.containsExactly(BigInteger.ONE.shiftLeft(8).add(BigInteger.valueOf(n)));
}
// check normal bitsize
for (long n : new long[] {0, 100, 200, 1700, 99000, 127000, 255000}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(bvmgr.makeBitvector(32, n), visitor);
assertThat(visitor.found).containsExactly(BigInteger.valueOf(n));
}
for (long n : new long[] {-100, -200, -1700, -99000, -127000, -255000}) {
ConstantsVisitor visitor = new ConstantsVisitor();
mgr.visit(bvmgr.makeBitvector(32, n), visitor);
assertThat(visitor.found)
.containsExactly(BigInteger.ONE.shiftLeft(32).add(BigInteger.valueOf(n)));
}
}
@Test
public void floatIdVisit() {
requireFloats();
FloatingPointType fp = FormulaType.getSinglePrecisionFloatingPointType();
FloatingPointFormula x = fpmgr.makeVariable("x", fp);
FloatingPointFormula y = fpmgr.makeVariable("y", fp);
for (Formula f :
ImmutableList.of(
fpmgr.equalWithFPSemantics(x, y),
fpmgr.add(x, y),
fpmgr.subtract(x, y),
fpmgr.multiply(x, y),
fpmgr.lessThan(x, y),
fpmgr.lessOrEquals(x, y),
fpmgr.greaterThan(x, y),
fpmgr.greaterOrEquals(x, y),
fpmgr.divide(x, y),
fpmgr.round(x, FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN),
// fpmgr.round(x, FloatingPointRoundingMode.NEAREST_TIES_AWAY),
fpmgr.round(x, FloatingPointRoundingMode.TOWARD_POSITIVE),
fpmgr.round(x, FloatingPointRoundingMode.TOWARD_NEGATIVE),
fpmgr.round(x, FloatingPointRoundingMode.TOWARD_ZERO))) {
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
Formula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
}
}
@Test
public void floatMoreVisit() {
requireFloats();
requireBitvectors();
FloatingPointType fp = FormulaType.getSinglePrecisionFloatingPointType();
FloatingPointFormula x = fpmgr.makeVariable("x", fp);
FloatingPointFormula y = fpmgr.makeVariable("x", fp);
BitvectorFormula z = bvmgr.makeVariable(32, "z");
checkKind(
fpmgr.castTo(x, true, FormulaType.getBitvectorTypeWithSize(32)),
FunctionDeclarationKind.FP_CASTTO_SBV);
checkKind(
fpmgr.castTo(x, true, FormulaType.getDoublePrecisionFloatingPointType()),
FunctionDeclarationKind.FP_CASTTO_FP);
checkKind(
fpmgr.castTo(x, false, FormulaType.getBitvectorTypeWithSize(32)),
FunctionDeclarationKind.FP_CASTTO_UBV);
checkKind(
fpmgr.castTo(x, false, FormulaType.getDoublePrecisionFloatingPointType()),
FunctionDeclarationKind.FP_CASTTO_FP);
checkKind(fpmgr.isNaN(x), FunctionDeclarationKind.FP_IS_NAN);
checkKind(fpmgr.isNegative(x), FunctionDeclarationKind.FP_IS_NEGATIVE);
checkKind(fpmgr.isInfinity(x), FunctionDeclarationKind.FP_IS_INF);
checkKind(fpmgr.isNormal(x), FunctionDeclarationKind.FP_IS_NORMAL);
checkKind(fpmgr.isSubnormal(x), FunctionDeclarationKind.FP_IS_SUBNORMAL);
checkKind(fpmgr.isZero(x), FunctionDeclarationKind.FP_IS_ZERO);
checkKind(fpmgr.abs(x), FunctionDeclarationKind.FP_ABS);
checkKind(fpmgr.max(x, y), FunctionDeclarationKind.FP_MAX);
checkKind(fpmgr.min(x, y), FunctionDeclarationKind.FP_MIN);
checkKind(fpmgr.sqrt(x), FunctionDeclarationKind.FP_SQRT);
if (Solvers.CVC4 != solverToUse()
&& Solvers.CVC5 != solverToUse()) { // CVC4/CVC5 do not support this operation
checkKind(fpmgr.toIeeeBitvector(x), FunctionDeclarationKind.FP_AS_IEEEBV);
}
checkKind(
fpmgr.castFrom(z, true, FormulaType.getSinglePrecisionFloatingPointType()),
FunctionDeclarationKind.BV_SCASTTO_FP);
checkKind(
fpmgr.castFrom(z, false, FormulaType.getSinglePrecisionFloatingPointType()),
FunctionDeclarationKind.BV_UCASTTO_FP);
}
@Test
public void bvVisit() throws SolverException, InterruptedException {
requireBitvectors();
BitvectorFormula x = bvmgr.makeVariable(5, "x");
for (BitvectorFormula f :
ImmutableList.of(bvmgr.extend(x, 10, true), bvmgr.extend(x, 10, false))) {
BitvectorFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(bmgr.not(bvmgr.equal(f, f2))).isUnsatisfiable();
}
}
@Test
public void bvVisitFunctionArgs() {
requireBitvectors();
BitvectorFormula x = bvmgr.makeVariable(5, "x");
BitvectorFormula y = bvmgr.makeVariable(5, "y");
for (Formula f :
ImmutableList.of(
bvmgr.lessOrEquals(x, y, true),
bvmgr.lessOrEquals(x, y, false),
bvmgr.lessThan(x, y, true),
bvmgr.lessThan(x, y, false),
bvmgr.greaterOrEquals(x, y, true),
bvmgr.greaterOrEquals(x, y, false),
bvmgr.greaterThan(x, y, true),
bvmgr.greaterThan(x, y, false),
bvmgr.add(x, y),
bvmgr.subtract(x, y),
bvmgr.multiply(x, y),
bvmgr.divide(x, y, true),
bvmgr.divide(x, y, false),
bvmgr.modulo(x, y, true),
bvmgr.modulo(x, y, false),
bvmgr.and(x, y),
bvmgr.or(x, y),
bvmgr.xor(x, y),
bvmgr.equal(x, y),
bvmgr.not(x),
bvmgr.negate(y))) {
mgr.visitRecursively(
f,
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula pF) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pDeclaration) {
switch (pDeclaration.getKind()) {
case NOT:
assertThat(pArgs).hasSize(1);
break;
case ITE:
assertThat(pArgs).hasSize(3);
break;
case EQ:
case BV_SLT:
case BV_SLE:
case BV_SGT:
case BV_SGE:
case BV_ULT:
case BV_ULE:
case BV_UGT:
case BV_UGE:
assertThat(pArgs).hasSize(2);
break;
case BV_NOT:
case BV_NEG:
// Yices is special in some cases
if (Solvers.YICES2 != solverToUse()) {
assertThat(pArgs).hasSize(1);
}
break;
case BV_ADD:
assertThat(pArgs).contains(x);
assertThat(pArgs).hasSize(2);
break;
case BV_MUL:
assertThat(pArgs).contains(y);
assertThat(pArgs).hasSize(2);
if (Solvers.YICES2 != solverToUse()) {
assertThat(pArgs).contains(x);
}
break;
default:
if (Solvers.YICES2 != solverToUse()) {
assertThat(pArgs).hasSize(2);
assertThat(pArgs).containsExactly(x, y);
}
}
return visitDefault(pF);
}
});
}
}
@Test
public void stringInBooleanFormulaIdVisit() throws SolverException, InterruptedException {
requireStrings();
StringFormula x = smgr.makeVariable("xVariable");
StringFormula y = smgr.makeVariable("yVariable");
RegexFormula r = smgr.makeRegex("regex1");
for (BooleanFormula f :
ImmutableList.of(
smgr.equal(x, y),
smgr.contains(x, y),
smgr.lessThan(x, y),
smgr.lessOrEquals(x, y),
smgr.greaterOrEquals(x, y),
smgr.greaterThan(x, y),
smgr.prefix(x, y),
smgr.suffix(x, y),
smgr.in(x, r))) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
BooleanFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(f).isEquivalentTo(f2);
}
}
@Test
public void stringInStringFormulaVisit() throws SolverException, InterruptedException {
requireStrings();
StringFormula x = smgr.makeVariable("xVariable");
StringFormula y = smgr.makeVariable("yVariable");
StringFormula z = smgr.makeString("zAsString");
IntegerFormula offset = imgr.makeVariable("offset");
IntegerFormula len = imgr.makeVariable("len");
ImmutableList.Builder<StringFormula> formulas =
ImmutableList.<StringFormula>builder()
.add(smgr.substring(x, offset, len))
.add(smgr.replace(x, y, z))
.add(smgr.charAt(x, offset))
.add(smgr.toStringFormula(offset))
.add(smgr.concat(x, y, z));
if (solverToUse() != Solvers.Z3) {
formulas.add(smgr.replaceAll(x, y, z)); // unsupported in Z3
}
for (StringFormula f : formulas.build()) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
StringFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(bmgr.not(smgr.equal(f, f2))).isUnsatisfiable();
}
}
@Test
public void stringInRegexFormulaVisit() {
requireStrings();
RegexFormula r = smgr.makeRegex("regex1");
RegexFormula s = smgr.makeRegex("regex2");
ImmutableList.Builder<RegexFormula> formulas =
ImmutableList.<RegexFormula>builder()
.add(smgr.union(r, s))
.add(smgr.closure(r))
.add(smgr.concat(r, r, r, s, s, s))
.add(smgr.cross(r));
if (solverToUse() != Solvers.Z3) {
formulas.add(smgr.difference(r, s)).add(smgr.complement(r));
// invalid function OTHER/INTERNAL in visitor, bug in Z3?
}
for (RegexFormula f : formulas.build()) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
RegexFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
}
}
@Test
public void stringInIntegerFormulaVisit() throws SolverException, InterruptedException {
requireStrings();
StringFormula x = smgr.makeVariable("xVariable");
StringFormula y = smgr.makeVariable("yVariable");
IntegerFormula offset = imgr.makeVariable("offset");
for (IntegerFormula f :
ImmutableList.of(smgr.indexOf(x, y, offset), smgr.length(x), smgr.toIntegerFormula(x))) {
mgr.visit(f, new FunctionDeclarationVisitorNoUF());
mgr.visit(f, new FunctionDeclarationVisitorNoOther());
IntegerFormula f2 = mgr.transformRecursively(f, new FormulaTransformationVisitor(mgr) {});
assertThat(f2).isEqualTo(f);
assertThatFormula(bmgr.not(imgr.equal(f, f2))).isUnsatisfiable();
}
}
private void checkKind(Formula f, FunctionDeclarationKind expected) {
FunctionDeclarationVisitorNoOther visitor = new FunctionDeclarationVisitorNoOther();
mgr.visit(f, visitor);
Truth.assert_()
.withMessage(
"declaration kind '%s' in function '%s' not available, only found '%s'.",
expected, f, visitor.found)
.that(visitor.found)
.contains(expected);
}
@Test
public void booleanIdVisitWithAtoms() {
IntegerFormula n12 = imgr.makeNumber(12);
IntegerFormula a = imgr.makeVariable("a");
IntegerFormula b = imgr.makeVariable("b");
IntegerFormula sum = imgr.add(a, b);
IntegerFormula diff = imgr.subtract(a, b);
IntegerFormula neg = imgr.negate(a);
BooleanFormula eq = imgr.equal(n12, a);
IntegerFormula ite = bmgr.ifThenElse(eq, sum, diff);
for (IntegerFormula f : ImmutableList.of(a, b, n12, neg, ite)) {
BooleanFormulaVisitor<BooleanFormula> identityVisitor =
new BooleanFormulaTransformationVisitor(mgr) {};
BooleanFormula bf = imgr.equal(n12, f);
assertThatFormula(bmgr.visit(bf, identityVisitor)).isEqualTo(bf);
}
}
/**
* A very basic test for the formula visitor, defines a visitor which gathers all found free
* variables.
*/
@Test
public void testFormulaVisitor() {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f = bmgr.or(imgr.equal(z, imgr.add(x, y)), imgr.equal(x, imgr.add(z, y)));
final Set<String> usedVariables = new HashSet<>();
FormulaVisitor<TraversalProcess> nameExtractor =
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula formula) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFreeVariable(Formula formula, String name) {
usedVariables.add(name);
return TraversalProcess.CONTINUE;
}
};
mgr.visitRecursively(f, nameExtractor);
assertThat(usedVariables).containsExactly("x", "y", "z");
}
@Test
public void testBooleanFormulaQuantifierHandling() throws Exception {
requireQuantifiers();
assume()
.withMessage("Princess does not support quantifier over boolean variables")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula constraint = qmgr.forall(ImmutableList.of(x), x);
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.visit(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
@Test
public void testBooleanFormulaQuantifierRecursiveHandling() throws Exception {
requireQuantifiers();
assume()
.withMessage("Princess does not support quantifier over boolean variables")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
BooleanFormula x = bmgr.makeVariable("x");
BooleanFormula constraint = qmgr.forall(ImmutableList.of(x), x);
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.transformRecursively(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
// Same as testBooleanFormulaQuantifierHandling but with Ints
@Test
public void testIntegerFormulaQuantifierHandlingUNSAT() throws Exception {
requireQuantifiers();
requireIntegers();
IntegerFormula x = imgr.makeVariable("x");
BooleanFormula xEq1 = bmgr.not(imgr.equal(imgr.makeNumber(1), x));
BooleanFormula constraint = qmgr.forall(ImmutableList.of(x), xEq1);
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.visit(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
@Test
public void testIntegerFormulaQuantifierHandlingTrivialSAT() throws Exception {
requireQuantifiers();
requireIntegers();
IntegerFormula x = imgr.makeVariable("x");
BooleanFormula xEqx = imgr.equal(x, x);
BooleanFormula constraint = qmgr.forall(ImmutableList.of(x), xEqx);
assertThatFormula(constraint).isSatisfiable();
BooleanFormula newConstraint =
bmgr.visit(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isSatisfiable();
}
@Test
public void testIntegerFormulaQuantifierSymbolsExtraction() {
requireQuantifiers();
requireIntegers();
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
BooleanFormula xEqy = imgr.equal(x, y);
// (x=y) && EX x: (X=y)
BooleanFormula constraint = bmgr.and(xEqy, qmgr.forall(ImmutableList.of(x), xEqy));
// The variable extraction should visit "x" and "y" only once,
// otherwise AbstractFormulaManager#extractVariables might throw an exception,
// when building an ImmutableMap.
Map<String, Formula> vars = mgr.extractVariables(constraint);
assertThat(vars).hasSize(2);
assertThat(vars).containsEntry(x.toString(), x);
assertThat(vars).containsEntry(y.toString(), y);
Map<String, Formula> varsAndUfs = mgr.extractVariablesAndUFs(constraint);
assertThat(varsAndUfs).hasSize(2);
assertThat(varsAndUfs).containsEntry(x.toString(), x);
assertThat(varsAndUfs).containsEntry(y.toString(), y);
}
@Test
public void testIntegerFormulaQuantifierHandlingTrivialUNSAT() throws Exception {
requireQuantifiers();
requireIntegers();
IntegerFormula x = imgr.makeVariable("x");
BooleanFormula notxEqx = bmgr.not(imgr.equal(x, x));
BooleanFormula constraint = qmgr.forall(ImmutableList.of(x), notxEqx);
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.visit(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
// The idea is to test quantifier (with bound variables),
// such that they might fail to reconstruct the bound vars properly.
// One of such failures may occur when the inner variables are substituted with outer vars.
// exists x . ( forall x . (x = 1))
// This is UNSAT as exists x_1 . ( forall x_2 . ( x_2 = 1 )).
// If however the bound var x is inproperly substituted this might happen:
// exists x_1 . ( forall x_2 . ( x_1 = 1 )) which is SAT
@Test
public void testNestedIntegerFormulaQuantifierHandling() throws Exception {
requireQuantifiers();
requireIntegers();
// Z3 returns UNKNOWN as its quantifiers can not handle this.
assume().that(solverToUse()).isNotEqualTo(Solvers.Z3);
IntegerFormula x = imgr.makeVariable("x");
BooleanFormula xEq1 = imgr.equal(x, imgr.makeNumber(1));
BooleanFormula constraint =
qmgr.exists(ImmutableList.of(x), qmgr.forall(ImmutableList.of(x), xEq1));
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.visit(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
// Same as testNestedIntegerFormulaQuantifierHandling but with a recursive visitor
@Test
public void testNestedIntegerFormulaQuantifierRecursiveHandling() throws Exception {
requireQuantifiers();
requireIntegers();
// Z3 returns UNKNOWN as its quantifiers can not handle this.
assume().that(solverToUse()).isNotEqualTo(Solvers.Z3);
IntegerFormula x = imgr.makeVariable("x");
BooleanFormula xEq1 = imgr.equal(x, imgr.makeNumber(1));
BooleanFormula constraint =
qmgr.exists(ImmutableList.of(x), qmgr.forall(ImmutableList.of(x), xEq1));
assertThatFormula(constraint).isUnsatisfiable();
BooleanFormula newConstraint =
bmgr.transformRecursively(constraint, new BooleanFormulaTransformationVisitor(mgr) {});
assertThatFormula(newConstraint).isUnsatisfiable();
}
@Test
public void testVisitingTrue() {
// Check that "true" is correctly treated as a constant.
BooleanFormula t = bmgr.makeBoolean(true);
final List<Boolean> containsTrue = new ArrayList<>();
mgr.visitRecursively(
t,
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitConstant(Formula f, Object o) {
if (f.equals(bmgr.makeBoolean(true))) {
containsTrue.add(true);
}
return TraversalProcess.CONTINUE;
}
});
assertThat(containsTrue).isNotEmpty();
}
@Test
public void testCorrectFunctionNames() {
BooleanFormula a = bmgr.makeVariable("a");
BooleanFormula b = bmgr.makeVariable("b");
BooleanFormula ab = bmgr.and(a, b);
final Set<String> found = new HashSet<>();
mgr.visitRecursively(
ab,
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
found.add(functionDeclaration.getName());
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFreeVariable(Formula f, String name) {
found.add(name);
return TraversalProcess.CONTINUE;
}
});
assertThat(found).containsAtLeast("a", "b");
assertThat(found).hasSize(3); // all the above plus the boolean "and" function
assertThat(found).doesNotContain(ab.toString());
}
@Test
public void recursiveTransformationVisitorTest() throws Exception {
BooleanFormula f =
bmgr.or(
imgr.equal(
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("y")), imgr.makeNumber(1)),
imgr.equal(imgr.makeVariable("z"), imgr.makeNumber(10)));
BooleanFormula transformed =
mgr.transformRecursively(
f,
new FormulaTransformationVisitor(mgr) {
@Override
public Formula visitFreeVariable(Formula formula, String name) {
return mgr.makeVariable(mgr.getFormulaType(formula), name + "'");
}
});
assertThatFormula(transformed)
.isEquivalentTo(
bmgr.or(
imgr.equal(
imgr.add(imgr.makeVariable("x'"), imgr.makeVariable("y'")), imgr.makeNumber(1)),
imgr.equal(imgr.makeVariable("z'"), imgr.makeNumber(10))));
}
@Test
public void recursiveTransformationVisitorTest2() throws Exception {
BooleanFormula f = imgr.equal(imgr.makeVariable("y"), imgr.makeNumber(1));
BooleanFormula transformed =
mgr.transformRecursively(
f,
new FormulaTransformationVisitor(mgr) {
@Override
public Formula visitFreeVariable(Formula formula, String name) {
return mgr.makeVariable(mgr.getFormulaType(formula), name + "'");
}
});
assertThatFormula(transformed)
.isEquivalentTo(imgr.equal(imgr.makeVariable("y'"), imgr.makeNumber(1)));
}
@Test
public void booleanRecursiveTraversalTest() {
BooleanFormula f =
bmgr.or(
bmgr.and(bmgr.makeVariable("x"), bmgr.makeVariable("y")),
bmgr.and(
bmgr.makeVariable("z"),
bmgr.makeVariable("d"),
imgr.equal(imgr.makeVariable("gg"), imgr.makeNumber(5))));
final Set<String> foundVars = new HashSet<>();
bmgr.visitRecursively(
f,
new DefaultBooleanFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault() {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitAtom(
BooleanFormula atom, FunctionDeclaration<BooleanFormula> funcDecl) {
if (funcDecl.getKind() == FunctionDeclarationKind.VAR) {
foundVars.add(funcDecl.getName());
}
return TraversalProcess.CONTINUE;
}
});
assertThat(foundVars).containsExactly("x", "y", "z", "d");
}
@Test
public void testTransformationInsideQuantifiers() {
requireQuantifiers();
// TODO Maybe rewrite using quantified integer variable to allow testing with Princess
assume()
.withMessage("Princess does not support quantifier over boolean variables")
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
BooleanFormula[] usedVars =
Stream.of("a", "b", "c", "d", "e", "f")
.map(var -> bmgr.makeVariable(var))
.toArray(BooleanFormula[]::new);
Fuzzer fuzzer = new Fuzzer(mgr, new Random(0));
List<BooleanFormula> quantifiedVars = ImmutableList.of(bmgr.makeVariable("a"));
BooleanFormula body = fuzzer.fuzz(30, usedVars);
BooleanFormula f = qmgr.forall(quantifiedVars, body);
BooleanFormula transformed =
bmgr.transformRecursively(
f,
new BooleanFormulaTransformationVisitor(mgr) {
@Override
public BooleanFormula visitAtom(
BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) {
if (decl.getKind() == FunctionDeclarationKind.VAR) {
// Uppercase all variables.
return bmgr.makeVariable(decl.getName().toUpperCase(Locale.getDefault()));
} else {
return pAtom;
}
}
});
assertThat(
mgr.extractVariables(transformed).keySet().stream()
.allMatch(pS -> pS.equals(pS.toUpperCase(Locale.getDefault()))))
.isTrue();
}
@Test
public void testTransformationInsideQuantifiersWithTrue()
throws SolverException, InterruptedException {
requireQuantifiers();
List<IntegerFormula> quantifiedVars = ImmutableList.of(imgr.makeVariable("x"));
BooleanFormula body = bmgr.makeTrue();
BooleanFormula f = qmgr.exists(quantifiedVars, body);
BooleanFormula transformed = qmgr.eliminateQuantifiers(f);
assertThat(mgr.extractVariablesAndUFs(transformed)).isEmpty();
assertThatFormula(transformed).isEquivalentTo(body);
}
@Test
public void testTransformationInsideQuantifiersWithFalse()
throws SolverException, InterruptedException {
requireQuantifiers();
List<IntegerFormula> quantifiedVars = ImmutableList.of(imgr.makeVariable("x"));
BooleanFormula body = bmgr.makeFalse();
BooleanFormula f = qmgr.exists(quantifiedVars, body);
BooleanFormula transformed = qmgr.eliminateQuantifiers(f);
assertThat(mgr.extractVariablesAndUFs(transformed)).isEmpty();
assertThatFormula(transformed).isEquivalentTo(body);
}
@Test
public void testTransformationInsideQuantifiersWithVariable()
throws SolverException, InterruptedException {
requireQuantifiers();
List<IntegerFormula> quantifiedVars = ImmutableList.of(imgr.makeVariable("x"));
BooleanFormula body = bmgr.makeVariable("b");
BooleanFormula f = qmgr.exists(quantifiedVars, body);
BooleanFormula transformed = qmgr.eliminateQuantifiers(f);
assertThat(mgr.extractVariablesAndUFs(transformed)).containsEntry("b", body);
assertThatFormula(transformed).isEquivalentTo(body);
}
@Test
public void extractionTest1() {
IntegerFormula v = imgr.makeVariable("v");
BooleanFormula q = fmgr.declareAndCallUF("q", FormulaType.BooleanType, v);
Map<String, Formula> mapping = mgr.extractVariablesAndUFs(q);
assertThat(mapping).hasSize(2);
assertThat(mapping).containsEntry("v", v);
assertThat(mapping).containsEntry("q", q);
}
@Test
public void extractionTest2() {
// the same as above, but with nullary UF.
IntegerFormula v = fmgr.declareAndCallUF("v", FormulaType.IntegerType);
BooleanFormula q = fmgr.declareAndCallUF("q", FormulaType.BooleanType, v);
Map<String, Formula> mapping = mgr.extractVariablesAndUFs(q);
Map<String, Formula> mapping2 = mgr.extractVariables(q);
// all solvers must provide all symbols
assertThat(mapping).hasSize(2);
assertThat(mapping).containsEntry("v", v);
assertThat(mapping).containsEntry("q", q);
// some solvers distinguish between nullary UFs and variables and do not provide variables
if (ImmutableList.of(Solvers.CVC4, Solvers.PRINCESS).contains(solverToUse())) {
assertThat(mapping2).isEmpty();
} else {
assertThat(mapping2).hasSize(1);
assertThat(mapping2).containsEntry("v", v);
}
}
private final FormulaVisitor<Formula> plainFunctionVisitor =
new DefaultFormulaVisitor<>() {
@Override
public Formula visitFunction(
Formula pF, List<Formula> args, FunctionDeclaration<?> pFunctionDeclaration) {
return fmgr.callUF(pFunctionDeclaration, args);
}
@Override
protected Formula visitDefault(Formula pF) {
return pF;
}
};
@Test
public void visitBooleanOperationWithMoreArgsTest() throws SolverException, InterruptedException {
BooleanFormula u = bmgr.makeVariable("u");
BooleanFormula v = bmgr.makeVariable("v");
BooleanFormula w = bmgr.makeVariable("w");
BooleanFormula fAnd = bmgr.and(u, v, w);
BooleanFormula fOr = bmgr.or(u, v, w);
Formula transformedAnd = mgr.visit(fAnd, plainFunctionVisitor);
assertThatFormula((BooleanFormula) transformedAnd).isEquisatisfiableTo(fAnd);
Formula transformedOr = mgr.visit(fOr, plainFunctionVisitor);
assertThatFormula((BooleanFormula) transformedOr).isEquisatisfiableTo(fOr);
}
@Test
public void visitArithmeticOperationWithMoreArgsTest()
throws SolverException, InterruptedException {
requireIntegers();
requireParser();
String abc =
"(declare-fun aa () Int) (declare-fun bb () Real)"
+ "(declare-fun cc () Real) (declare-fun dd () Int)";
BooleanFormula sum = mgr.parse(abc + "(assert (= 0 (+ aa bb cc dd)))");
BooleanFormula equals = mgr.parse(abc + "(assert (= aa bb cc dd))");
BooleanFormula distinct = mgr.parse(abc + "(assert (distinct aa bb cc dd))");
BooleanFormula less = mgr.parse(abc + "(assert (< aa bb cc dd))");
BooleanFormula lessEquals = mgr.parse(abc + "(assert (<= aa bb cc dd))");
BooleanFormula greater = mgr.parse(abc + "(assert (> aa bb cc dd))");
BooleanFormula greaterEquals = mgr.parse(abc + "(assert (>= aa bb cc dd))");
for (BooleanFormula bf :
ImmutableList.of(sum, equals, distinct, less, lessEquals, greater, greaterEquals)) {
Formula transformed = mgr.visit(bf, plainFunctionVisitor);
assertThatFormula((BooleanFormula) transformed).isEquisatisfiableTo(bf);
}
}
@Test
public void extractionArguments() {
requireIntegers();
// Create the variables and uf
IntegerFormula a = imgr.makeVariable("a");
IntegerFormula b = imgr.makeVariable("b");
IntegerFormula ab = imgr.add(a, b);
BooleanFormula uf = fmgr.declareAndCallUF("testFunc", FormulaType.BooleanType, a, b, ab);
FormulaVisitor<Collection<Formula>> argCollectingVisitor =
new DefaultFormulaVisitor<>() {
final Collection<Formula> usedArgs = new LinkedHashSet<>();
@Override
public Collection<Formula> visitFunction(
Formula pF, List<Formula> args, FunctionDeclaration<?> pFunctionDeclaration) {
usedArgs.addAll(args);
return usedArgs;
}
@Override
protected Collection<Formula> visitDefault(Formula pF) {
return usedArgs;
}
};
Collection<Formula> usedArgs = mgr.visit(uf, argCollectingVisitor);
assertThat(usedArgs).hasSize(3);
assertThat(usedArgs).containsExactly(a, b, ab);
Map<String, Formula> vars = mgr.extractVariables(uf);
assertThat(vars).hasSize(2);
assertThat(vars.keySet()).containsExactly("a", "b");
Map<String, Formula> varsUfs = mgr.extractVariablesAndUFs(uf);
assertThat(varsUfs).hasSize(3);
assertThat(varsUfs.keySet()).containsExactly("a", "b", "testFunc");
}
@Test
public void extractionDeclarations() {
requireIntegers();
// Create the variables and uf
IntegerFormula a = imgr.makeVariable("a");
IntegerFormula b = imgr.makeVariable("b");
IntegerFormula ab = imgr.add(a, b);
BooleanFormula uf1 = fmgr.declareAndCallUF("testFunc", FormulaType.BooleanType, a, b, ab);
BooleanFormula uf2 = fmgr.declareAndCallUF("testFunc", FormulaType.BooleanType, ab, b, a);
BooleanFormula f = bmgr.and(uf1, uf2);
final Collection<Formula> usedArgs = new LinkedHashSet<>();
final List<FunctionDeclaration<?>> usedDecls = new ArrayList<>();
FormulaVisitor<TraversalProcess> argCollectingVisitor =
new DefaultFormulaVisitor<>() {
@Override
public TraversalProcess visitFunction(
Formula pF, List<Formula> args, FunctionDeclaration<?> pFunctionDeclaration) {
usedArgs.addAll(args);
usedDecls.add(pFunctionDeclaration);
return visitDefault(pF);
}
@Override
protected TraversalProcess visitDefault(Formula pF) {
return TraversalProcess.CONTINUE;
}
};
mgr.visitRecursively(f, argCollectingVisitor);
// check general stuff about variables, copied from above
assertThat(usedArgs).hasSize(5);
assertThat(usedArgs).containsExactly(uf1, uf2, a, b, ab);
Map<String, Formula> vars = mgr.extractVariables(f);
assertThat(vars).hasSize(2);
assertThat(vars.keySet()).containsExactly("a", "b");
Map<String, Formula> varsUfs = mgr.extractVariablesAndUFs(f);
assertThat(varsUfs).hasSize(3);
assertThat(varsUfs.keySet()).containsExactly("a", "b", "testFunc");
// check correct traversal order of the functions
assertThat(usedDecls).hasSize(4);
assertThat(usedDecls.get(0).getKind()).isEqualTo(FunctionDeclarationKind.AND);
assertThat(usedDecls.get(1).getName()).isEqualTo("testFunc");
assertThat(usedDecls.get(2).getKind()).isEqualTo(FunctionDeclarationKind.ADD);
assertThat(usedDecls.get(3).getName()).isEqualTo("testFunc");
// check UF-equality. This check went wrong in CVC4 and was fixed.
assertThat(usedDecls.get(1)).isEqualTo(usedDecls.get(3));
}
}
| 44,973 | 37.604292 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/StringFormulaManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
@SuppressWarnings("ConstantConditions")
@SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "test code")
public class StringFormulaManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private static final ImmutableList<String> WORDS =
ImmutableList.of(
"",
"0",
"1",
"10",
"a",
"b",
"A",
"B",
"aa",
"Aa",
"aA",
"AA",
"ab",
"aB",
"Ab",
"AB",
"ac",
"bb",
"aaa",
"Aaa",
"aAa",
"aAA",
"aab",
"aaabbb",
"bbbccc",
"abcde",
"abdde",
"abcdf",
"abchurrdurr",
"abcdefaaaaa");
private StringFormula hello;
private RegexFormula a2z;
@Before
public void setup() {
requireStrings();
hello = smgr.makeString("hello");
a2z = smgr.range('a', 'z');
}
// Utility methods
private void assertEqual(IntegerFormula num1, IntegerFormula num2)
throws SolverException, InterruptedException {
assertThatFormula(imgr.equal(num1, num2)).isTautological();
}
private void assertDistinct(IntegerFormula num1, IntegerFormula num2)
throws SolverException, InterruptedException {
assertThatFormula(imgr.distinct(List.of(num1, num2))).isTautological();
}
private void assertEqual(StringFormula str1, StringFormula str2)
throws SolverException, InterruptedException {
assertThatFormula(smgr.equal(str1, str2)).isTautological();
}
private void assertDistinct(StringFormula str1, StringFormula str2)
throws SolverException, InterruptedException {
assertThatFormula(smgr.equal(str1, str2)).isUnsatisfiable();
}
// Tests
@Test
public void testRegexAll() throws SolverException, InterruptedException {
RegexFormula regex = smgr.all();
assertThatFormula(smgr.in(hello, regex)).isSatisfiable();
}
@Test
public void testRegexAll3() throws SolverException, InterruptedException {
// This is not ALL_CHAR! This matches ".*" literally!
RegexFormula regex = smgr.makeRegex(".*");
assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable();
assertThatFormula(smgr.in(smgr.makeString(".*"), regex)).isSatisfiable();
}
@Test
public void testRegexAllChar() throws SolverException, InterruptedException {
RegexFormula regexAllChar = smgr.allChar();
assertThatFormula(smgr.in(smgr.makeString("a"), regexAllChar)).isSatisfiable();
assertThatFormula(smgr.in(smgr.makeString("ab"), regexAllChar)).isUnsatisfiable();
assertThatFormula(smgr.in(smgr.makeString(""), regexAllChar)).isUnsatisfiable();
assertThatFormula(smgr.in(smgr.makeString("ab"), smgr.times(regexAllChar, 2))).isSatisfiable();
assertThatFormula(
smgr.in(smgr.makeVariable("x"), smgr.intersection(smgr.range('9', 'a'), regexAllChar)))
.isSatisfiable();
RegexFormula regexDot = smgr.makeRegex(".");
assertThatFormula(smgr.in(smgr.makeString("a"), regexDot)).isUnsatisfiable();
}
@Test
public void testRegexAllCharUnicode() throws SolverException, InterruptedException {
RegexFormula regexAllChar = smgr.allChar();
// Single characters.
assertThatFormula(smgr.in(smgr.makeString("\\u0394"), regexAllChar)).isSatisfiable();
assertThatFormula(smgr.in(smgr.makeString("\\u{1fa6a}"), regexAllChar)).isSatisfiable();
// Combining characters are not matched as one character.
assertThatFormula(smgr.in(smgr.makeString("a\\u0336"), regexAllChar)).isUnsatisfiable();
assertThatFormula(smgr.in(smgr.makeString("\\n"), regexAllChar)).isUnsatisfiable();
if (ImmutableList.of(Solvers.CVC4, Solvers.CVC5).contains(solverToUse())) {
// CVC4 and CVC5 do not support Unicode characters.
assertThrows(Exception.class, () -> smgr.range('a', 'Δ'));
} else {
// Z3 and other solvers support Unicode characters in the theory of strings.
assertThatFormula(
smgr.in(smgr.makeVariable("x"), smgr.union(smgr.range('a', 'Δ'), regexAllChar)))
.isSatisfiable();
// Combining characters are not matched as one character.
// Non-ascii non-printable characters should use the codepoint representation
assertThatFormula(smgr.in(smgr.makeString("Δ"), regexAllChar)).isUnsatisfiable();
}
}
@Test
public void testStringRegex2() throws SolverException, InterruptedException {
RegexFormula regex = smgr.concat(smgr.closure(a2z), smgr.makeRegex("ll"), smgr.closure(a2z));
assertThatFormula(smgr.in(hello, regex)).isSatisfiable();
}
@Test
public void testStringRegex3() throws SolverException, InterruptedException {
RegexFormula regex = smgr.makeRegex(".*ll.*");
assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable();
}
@Test
public void testEmptyRegex() throws SolverException, InterruptedException {
RegexFormula regex = smgr.none();
assertThatFormula(smgr.in(hello, regex)).isUnsatisfiable();
}
@Test
public void testRegexUnion() throws SolverException, InterruptedException {
RegexFormula regex = smgr.union(smgr.makeRegex("a"), smgr.makeRegex("b"));
assertThatFormula(smgr.in(smgr.makeString("a"), regex)).isSatisfiable();
assertThatFormula(smgr.in(smgr.makeString("b"), regex)).isSatisfiable();
assertThatFormula(smgr.in(smgr.makeString("c"), regex)).isUnsatisfiable();
}
@Test
public void testRegexIntersection() throws SolverException, InterruptedException {
RegexFormula regex = smgr.intersection(smgr.makeRegex("a"), smgr.makeRegex("b"));
StringFormula variable = smgr.makeVariable("var");
assertThatFormula(smgr.in(variable, regex)).isUnsatisfiable();
regex =
smgr.intersection(
smgr.union(smgr.makeRegex("a"), smgr.makeRegex("b")),
smgr.union(smgr.makeRegex("b"), smgr.makeRegex("c")));
assertThatFormula(smgr.in(smgr.makeString("a"), regex)).isUnsatisfiable();
assertThatFormula(smgr.in(smgr.makeString("b"), regex)).isSatisfiable();
}
@Test
public void testRegexDifference() throws SolverException, InterruptedException {
RegexFormula regex =
smgr.difference(smgr.union(smgr.makeRegex("a"), smgr.makeRegex("b")), smgr.makeRegex("b"));
assertThatFormula(smgr.in(smgr.makeString("a"), regex)).isSatisfiable();
assertThatFormula(smgr.in(smgr.makeString("b"), regex)).isUnsatisfiable();
}
@Test
public void testStringConcat() throws SolverException, InterruptedException {
StringFormula str1 = smgr.makeString("hello");
StringFormula str2 = smgr.makeString("world");
StringFormula concat = smgr.concat(str1, str2);
StringFormula complete = smgr.makeString("helloworld");
assertEqual(concat, complete);
}
@Test
public void testStringConcatEmpty() throws SolverException, InterruptedException {
StringFormula empty = smgr.makeString("");
assertEqual(empty, smgr.concat(ImmutableList.of()));
assertEqual(empty, smgr.concat(empty));
assertEqual(empty, smgr.concat(empty, empty));
assertEqual(empty, smgr.concat(ImmutableList.of(empty, empty, empty, empty)));
}
@Test
public void testStringPrefixSuffixConcat() throws SolverException, InterruptedException {
// check whether "prefix + suffix == concat"
StringFormula prefix = smgr.makeVariable("prefix");
StringFormula suffix = smgr.makeVariable("suffix");
StringFormula concat = smgr.makeVariable("concat");
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, concat),
smgr.suffix(suffix, concat),
imgr.equal(
smgr.length(concat), imgr.add(smgr.length(prefix), smgr.length(suffix)))))
.implies(smgr.equal(concat, smgr.concat(prefix, suffix)));
}
@Test
public void testStringPrefixSuffix() throws SolverException, InterruptedException {
// check whether "prefix == suffix iff equal length"
StringFormula prefix = smgr.makeVariable("prefix");
StringFormula suffix = smgr.makeVariable("suffix");
assertThatFormula(bmgr.and(smgr.prefix(prefix, suffix), smgr.suffix(suffix, prefix)))
.implies(smgr.equal(prefix, suffix));
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, suffix), imgr.equal(smgr.length(prefix), smgr.length(suffix))))
.implies(smgr.equal(prefix, suffix));
assertThatFormula(
bmgr.and(
smgr.suffix(suffix, prefix), imgr.equal(smgr.length(prefix), smgr.length(suffix))))
.implies(smgr.equal(prefix, suffix));
}
@Test
public void testStringToIntConversion() throws SolverException, InterruptedException {
IntegerFormula ten = imgr.makeNumber(10);
StringFormula zeroStr = smgr.makeString("0");
for (int i = 0; i < 100; i += 7) {
StringFormula str = smgr.makeString(Integer.toString(i));
IntegerFormula num = imgr.makeNumber(i);
IntegerFormula numInc = imgr.makeNumber(i + 1);
assertEqual(str, smgr.toStringFormula(num));
assertDistinct(str, smgr.toStringFormula(numInc));
assertDistinct(str, smgr.toStringFormula(imgr.add(num, numInc)));
assertEqual(num, smgr.toIntegerFormula(str));
assertDistinct(numInc, smgr.toIntegerFormula(str));
assertEqual(imgr.multiply(num, ten), smgr.toIntegerFormula(smgr.concat(str, zeroStr)));
assertDistinct(imgr.multiply(numInc, ten), smgr.toIntegerFormula(smgr.concat(str, zeroStr)));
assertEqual(num, smgr.toIntegerFormula(smgr.toStringFormula(num)));
assertEqual(numInc, smgr.toIntegerFormula(smgr.toStringFormula(numInc)));
}
}
@Test
public void testStringToIntConversionCornerCases() throws SolverException, InterruptedException {
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-1")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-12")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-123")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("-1234")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-1")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-12")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-123")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("-1234")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("a")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("1a")));
assertEqual(imgr.makeNumber(-1), smgr.toIntegerFormula(smgr.makeString("a1")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("a")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("1a")));
assertDistinct(imgr.makeNumber(-12), smgr.toIntegerFormula(smgr.makeString("a1")));
}
@Test
public void testIntToStringConversionCornerCases() throws SolverException, InterruptedException {
assertEqual(smgr.makeString("123"), smgr.toStringFormula(imgr.makeNumber(123)));
assertEqual(smgr.makeString("1"), smgr.toStringFormula(imgr.makeNumber(1)));
assertEqual(smgr.makeString("0"), smgr.toStringFormula(imgr.makeNumber(0)));
assertEqual(smgr.makeString(""), smgr.toStringFormula(imgr.makeNumber(-1)));
assertEqual(smgr.makeString(""), smgr.toStringFormula(imgr.makeNumber(-123)));
assertDistinct(smgr.makeString("1"), smgr.toStringFormula(imgr.makeNumber(-1)));
}
@Test
public void testStringLength() throws SolverException, InterruptedException {
assertEqual(imgr.makeNumber(0), smgr.length(smgr.makeString("")));
assertEqual(imgr.makeNumber(1), smgr.length(smgr.makeString("a")));
assertEqual(imgr.makeNumber(2), smgr.length(smgr.makeString("aa")));
assertEqual(imgr.makeNumber(9), smgr.length(smgr.makeString("aaabbbccc")));
assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("")));
assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("a")));
assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("aa")));
assertDistinct(imgr.makeNumber(5), smgr.length(smgr.makeString("aaabbbcc")));
}
@Test
public void testStringLengthWithVariable() throws SolverException, InterruptedException {
StringFormula var = smgr.makeVariable("var");
assertThatFormula(imgr.equal(imgr.makeNumber(0), smgr.length(var)))
.implies(smgr.equal(var, smgr.makeString("")));
assertThatFormula(
bmgr.and(
imgr.equal(imgr.makeNumber(5), smgr.length(var)),
smgr.prefix(smgr.makeString("aba"), var),
smgr.suffix(smgr.makeString("aba"), var)))
.implies(smgr.equal(smgr.makeVariable("var"), smgr.makeString("ababa")));
assertThatFormula(
bmgr.and(
imgr.equal(imgr.makeNumber(4), smgr.length(var)),
smgr.prefix(smgr.makeString("aba"), var),
smgr.suffix(smgr.makeString("aba"), var)))
.isUnsatisfiable();
assertThatFormula(
bmgr.and(
imgr.equal(imgr.makeNumber(4), smgr.length(var)),
smgr.prefix(smgr.makeString("ab"), var),
smgr.suffix(smgr.makeString("ba"), var),
smgr.equal(smgr.makeString("c"), smgr.charAt(var, imgr.makeNumber(3)))))
.isUnsatisfiable();
assertThatFormula(
bmgr.and(
imgr.equal(imgr.makeNumber(5), smgr.length(var)),
smgr.prefix(smgr.makeString("ab"), var),
smgr.suffix(smgr.makeString("ba"), var),
smgr.equal(smgr.makeString("c"), smgr.charAt(var, imgr.makeNumber(3)))))
.implies(smgr.equal(smgr.makeVariable("var"), smgr.makeString("abcba")));
}
@Test
public void testStringLengthPositiv() throws SolverException, InterruptedException {
assertThatFormula(imgr.lessOrEquals(imgr.makeNumber(0), smgr.length(smgr.makeVariable("x"))))
.isTautological();
assertThatFormula(imgr.greaterThan(imgr.makeNumber(0), smgr.length(smgr.makeVariable("x"))))
.isUnsatisfiable();
}
@Test
public void testStringCompare() throws SolverException, InterruptedException {
assume()
.withMessage("Solver is quite slow for this example")
.that(solverToUse())
.isNoneOf(Solvers.Z3, Solvers.CVC5);
// TODO regression:
// - the Z3 library was able to solve this in v4.11.2, but no longer in v4.12.1-glibc_2.27.
// - CVC5 was able to solve this in v1.0.2, but no longer in v1.0.5
StringFormula var1 = smgr.makeVariable("0");
StringFormula var2 = smgr.makeVariable("1");
assertThatFormula(bmgr.and(smgr.lessOrEquals(var1, var2), smgr.greaterOrEquals(var1, var2)))
.implies(smgr.equal(var1, var2));
assertThatFormula(smgr.equal(var1, var2))
.implies(bmgr.and(smgr.lessOrEquals(var1, var2), smgr.greaterOrEquals(var1, var2)));
}
/** Test const Strings = String variables + prefix and suffix constraints. */
@Test
public void testConstStringEqStringVar() throws SolverException, InterruptedException {
String string1 = "";
String string2 = "a";
String string3 = "ab";
String string4 = "abcdefghijklmnopqrstuvwxyz";
StringFormula string1c = smgr.makeString(string1);
StringFormula string2c = smgr.makeString(string2);
StringFormula string3c = smgr.makeString(string3);
StringFormula string4c = smgr.makeString(string4);
StringFormula string1v = smgr.makeVariable("string1v");
StringFormula string2v = smgr.makeVariable("string1v");
StringFormula string3v = smgr.makeVariable("string1v");
StringFormula string4v = smgr.makeVariable("string1v");
BooleanFormula formula =
bmgr.and(
smgr.equal(string1c, string1v),
smgr.equal(string2c, string2v),
smgr.equal(string3c, string3v),
smgr.equal(string4c, string4v));
BooleanFormula string1PrefixFormula =
bmgr.and(
smgr.prefix(string1c, string1v),
bmgr.not(smgr.prefix(string2c, string1v)),
bmgr.not(smgr.prefix(string3c, string1v)),
bmgr.not(smgr.prefix(string4c, string1v)));
BooleanFormula string2PrefixFormula =
bmgr.and(
smgr.prefix(string1c, string2v),
smgr.prefix(string2c, string2v),
bmgr.not(smgr.prefix(string3c, string2v)),
bmgr.not(smgr.prefix(string4c, string2v)));
BooleanFormula string3PrefixFormula =
bmgr.and(
smgr.prefix(string1c, string3v),
smgr.prefix(string2c, string3v),
smgr.prefix(string3c, string3v),
bmgr.not(smgr.prefix(string4c, string3v)));
BooleanFormula string4PrefixFormula =
bmgr.and(
smgr.prefix(string1c, string4v),
smgr.prefix(string2c, string4v),
smgr.prefix(string3c, string4v),
smgr.prefix(string4c, string4v));
BooleanFormula string1SuffixFormula =
bmgr.and(
smgr.suffix(string1c, string1v),
bmgr.not(smgr.suffix(string2c, string1v)),
bmgr.not(smgr.suffix(string3c, string1v)),
bmgr.not(smgr.suffix(string4c, string1v)));
BooleanFormula string2SuffixFormula =
bmgr.and(
smgr.suffix(string1c, string2v),
bmgr.not(smgr.suffix(string3c, string2v)),
bmgr.not(smgr.suffix(string4c, string2v)));
BooleanFormula string3SuffixFormula =
bmgr.and(
smgr.suffix(string1c, string3v),
smgr.suffix(string3c, string3v),
bmgr.not(smgr.suffix(string4c, string3v)));
BooleanFormula string4SuffixFormula =
bmgr.and(smgr.suffix(string1c, string4v), smgr.suffix(string4c, string4v));
assertThatFormula(bmgr.and(formula))
.implies(
bmgr.and(
string1PrefixFormula,
string2PrefixFormula,
string3PrefixFormula,
string4PrefixFormula,
string1SuffixFormula,
string2SuffixFormula,
string3SuffixFormula,
string4SuffixFormula));
}
/** Test String variables with negative length (UNSAT). */
@Test
public void testStringVariableLengthNegative() throws SolverException, InterruptedException {
StringFormula stringVariable1 = smgr.makeVariable("zeroLength");
StringFormula stringVariable2 = smgr.makeVariable("negLength");
// SAT + UNSAT Formula -> UNSAT
assertThatFormula(
bmgr.and(
imgr.equal(smgr.length(stringVariable1), imgr.makeNumber(0)),
imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-100))))
.isUnsatisfiable();
// UNSAT below
assertThatFormula(imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-1)))
.isUnsatisfiable();
assertThatFormula(imgr.equal(smgr.length(stringVariable2), imgr.makeNumber(-100)))
.isUnsatisfiable();
}
/**
* Test String formulas with inequalities in the negative range.
*
* <p>-10000 < stringVariable length < 0 -> UNSAT
*
* <p>-10000 < stringVariable length < -1 -> UNSAT
*
* <p>-10000 <= stringVariable length <= -1 -> UNSAT
*
* <p>-10000 <= stringVariable length <= 0 AND stringVariable != "" -> UNSAT
*
* <p>-10000 <= stringVariable length <= 0 -> SAT implies stringVariable = ""
*/
@Test
public void testStringLengthInequalityNegativeRange()
throws SolverException, InterruptedException {
StringFormula stringVariable = smgr.makeVariable("stringVariable");
IntegerFormula stringVariableLength = smgr.length(stringVariable);
IntegerFormula minusTenThousand = imgr.makeNumber(-10000);
IntegerFormula minusOne = imgr.makeNumber(-1);
IntegerFormula zero = imgr.makeNumber(0);
// -10000 < stringVariable length < 0 -> UNSAT
assertThatFormula(
bmgr.and(
imgr.lessThan(minusTenThousand, stringVariableLength),
imgr.lessThan(stringVariableLength, zero)))
.isUnsatisfiable();
// -10000 < stringVariable length < -1 -> UNSAT
assertThatFormula(
bmgr.and(
imgr.lessThan(minusTenThousand, stringVariableLength),
imgr.lessThan(stringVariableLength, minusOne)))
.isUnsatisfiable();
// -10000 <= stringVariable length <= -1 -> UNSAT
assertThatFormula(
bmgr.and(
imgr.lessOrEquals(minusTenThousand, stringVariableLength),
imgr.lessOrEquals(stringVariableLength, minusOne)))
.isUnsatisfiable();
// -10000 <= stringVariable length <= 0 AND stringVariable != "" -> UNSAT
assertThatFormula(
bmgr.and(
imgr.lessOrEquals(minusTenThousand, stringVariableLength),
imgr.lessOrEquals(stringVariableLength, zero),
bmgr.not(smgr.equal(stringVariable, smgr.makeString("")))))
.isUnsatisfiable();
// -10000 <= stringVariable length <= 0 -> SAT implies stringVariable = ""
assertThatFormula(
bmgr.and(
imgr.lessOrEquals(minusTenThousand, stringVariableLength),
imgr.lessOrEquals(stringVariableLength, zero)))
.implies(smgr.equal(stringVariable, smgr.makeString("")));
}
/**
* Test String formulas with inequalities in the negative range.
*
* <p>0 < stringVariable length < 1 -> UNSAT
*
* <p>0 < stringVariable length < 2 -> SAT
*
* <p>0 <= stringVariable length < 1 -> SAT implies stringVariable = ""
*
* <p>1 < stringVariable length < 3 -> SAT implies stringVariable length = 2
*/
@Test
public void testStringLengthInequalityPositiveRange()
throws SolverException, InterruptedException {
StringFormula stringVariable = smgr.makeVariable("stringVariable");
IntegerFormula stringVariableLength = smgr.length(stringVariable);
IntegerFormula three = imgr.makeNumber(3);
IntegerFormula two = imgr.makeNumber(2);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula zero = imgr.makeNumber(0);
// 0 < stringVariable length < 1 -> UNSAT
assertThatFormula(
bmgr.and(
imgr.lessThan(zero, stringVariableLength),
imgr.lessThan(stringVariableLength, one)))
.isUnsatisfiable();
// 0 < stringVariable length < 2 -> SAT
assertThatFormula(
bmgr.and(
imgr.lessThan(zero, stringVariableLength),
imgr.lessThan(stringVariableLength, two)))
.isSatisfiable();
// 0 <= stringVariable length < 1 -> SAT implies stringVariable = ""
assertThatFormula(
bmgr.and(
imgr.lessOrEquals(zero, stringVariableLength),
imgr.lessThan(stringVariableLength, one)))
.implies(smgr.equal(stringVariable, smgr.makeString("")));
// 1 < stringVariable length < 3 -> SAT implies stringVariable length = 2
assertThatFormula(
bmgr.and(
imgr.lessThan(one, stringVariableLength),
imgr.lessThan(stringVariableLength, three)))
.implies(imgr.equal(smgr.length(stringVariable), two));
}
/** Test simple String lexicographic ordering (< <= > >=) for constant Strings. */
@Test
public void testSimpleConstStringLexicographicOrdering()
throws SolverException, InterruptedException {
List<String> words = ImmutableList.sortedCopyOf(WORDS);
for (int i = 1; i < words.size(); i++) {
StringFormula word1 = smgr.makeString(words.get(i - 1));
StringFormula word2 = smgr.makeString(words.get(i));
assertThatFormula(smgr.lessThan(word1, word1)).isUnsatisfiable();
assertThatFormula(smgr.lessOrEquals(word1, word1)).isSatisfiable();
assertThatFormula(smgr.greaterOrEquals(word1, word1)).isSatisfiable();
assertThatFormula(smgr.lessThan(word1, word2)).isSatisfiable();
assertThatFormula(smgr.lessOrEquals(word1, word2)).isSatisfiable();
assertThatFormula(smgr.greaterThan(word1, word2)).isUnsatisfiable();
assertThatFormula(smgr.greaterOrEquals(word1, word2)).isUnsatisfiable();
}
}
/** Test simple String lexicographic ordering (< <= > >=) for String variables. */
@Test
public void testSimpleStringVariableLexicographicOrdering()
throws SolverException, InterruptedException {
StringFormula a = smgr.makeString("a");
StringFormula b = smgr.makeString("b");
StringFormula ab = smgr.makeString("ab");
StringFormula abc = smgr.makeString("abc");
StringFormula abd = smgr.makeString("abd");
StringFormula abe = smgr.makeString("abe");
StringFormula abaab = smgr.makeString("abaab");
StringFormula abbab = smgr.makeString("abbab");
StringFormula abcab = smgr.makeString("abcab");
StringFormula stringVariable = smgr.makeVariable("stringVariable");
assertThatFormula(
bmgr.and(
smgr.lessThan(a, stringVariable),
smgr.lessThan(stringVariable, b),
imgr.equal(imgr.makeNumber(0), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, smgr.makeString("")));
assertThatFormula(
bmgr.and(
smgr.lessOrEquals(a, stringVariable),
smgr.lessThan(stringVariable, b),
imgr.equal(imgr.makeNumber(1), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, smgr.makeString("a")));
assertThatFormula(
bmgr.and(
smgr.lessThan(a, stringVariable),
smgr.lessOrEquals(stringVariable, b),
imgr.equal(imgr.makeNumber(1), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, b));
assertThatFormula(
bmgr.and(
smgr.lessOrEquals(abc, stringVariable),
smgr.lessThan(stringVariable, abd),
imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, abc));
assertThatFormula(
bmgr.and(
smgr.lessThan(abc, stringVariable),
smgr.lessThan(stringVariable, abe),
imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, abd));
assertThatFormula(
bmgr.and(
smgr.lessThan(abc, stringVariable),
smgr.lessOrEquals(stringVariable, abd),
imgr.equal(imgr.makeNumber(3), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, abd));
assertThatFormula(
bmgr.and(
smgr.lessThan(abaab, stringVariable),
smgr.lessThan(stringVariable, abcab),
smgr.prefix(ab, stringVariable),
smgr.suffix(ab, stringVariable),
imgr.equal(imgr.makeNumber(5), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, abbab));
}
/** Takeaway: invalid positions always refer to the empty string! */
@Test
public void testCharAtWithConstString() throws SolverException, InterruptedException {
StringFormula empty = smgr.makeString("");
StringFormula a = smgr.makeString("a");
StringFormula b = smgr.makeString("b");
StringFormula ab = smgr.makeString("ab");
assertEqual(smgr.charAt(empty, imgr.makeNumber(1)), empty);
assertEqual(smgr.charAt(empty, imgr.makeNumber(0)), empty);
assertEqual(smgr.charAt(empty, imgr.makeNumber(-1)), empty);
assertDistinct(smgr.charAt(a, imgr.makeNumber(-1)), a);
assertEqual(smgr.charAt(a, imgr.makeNumber(-1)), empty);
assertEqual(smgr.charAt(a, imgr.makeNumber(0)), a);
assertDistinct(smgr.charAt(a, imgr.makeNumber(1)), a);
assertEqual(smgr.charAt(a, imgr.makeNumber(1)), empty);
assertDistinct(smgr.charAt(a, imgr.makeNumber(2)), a);
assertEqual(smgr.charAt(a, imgr.makeNumber(2)), empty);
assertEqual(smgr.charAt(ab, imgr.makeNumber(0)), a);
assertEqual(smgr.charAt(ab, imgr.makeNumber(1)), b);
assertDistinct(smgr.charAt(ab, imgr.makeNumber(0)), b);
assertDistinct(smgr.charAt(ab, imgr.makeNumber(1)), a);
}
/**
* Test escapecharacter treatment. Escape characters are treated as a single char! Example:
* "a\u1234T" has "a" at position 0, "\u1234" at position 1 and "T" at position 2
*
* <p>SMTLIB2 uses an escape sequence for the numerals of the sort: {1234}.
*/
@Test
public void testCharAtWithSpecialCharacters() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does only support 2 byte unicode", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
StringFormula num1 = smgr.makeString("1");
StringFormula u = smgr.makeString("u");
StringFormula curlyOpen = smgr.makeString("{");
StringFormula curlyClose = smgr.makeString("}");
StringFormula u1234WOEscape = smgr.makeString("u1234");
StringFormula au1234WOEscape = smgr.makeString("au1234");
// Java needs a double {{ as the first one is needed as an escape char for the second, this is a
// workaround
String workaround = "au{1234}";
StringFormula au1234WOEscapeCurly = smgr.makeString(workaround);
StringFormula backSlash = smgr.makeString("\\");
StringFormula a = smgr.makeString("a");
StringFormula b = smgr.makeString("b");
StringFormula u1234 = smgr.makeString("\\u{1234}");
StringFormula au1234b = smgr.makeString("a\\u{1234}b");
StringFormula stringVariable = smgr.makeVariable("stringVariable");
// Javas backslash (double written) is just 1 char
assertThatFormula(imgr.equal(smgr.length(backSlash), imgr.makeNumber(1))).isSatisfiable();
assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(0)), stringVariable))
.implies(smgr.equal(stringVariable, a));
// It seems like CVC4 sees the backslash as its own char!
assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(1)), stringVariable))
.implies(smgr.equal(stringVariable, u1234));
assertThatFormula(smgr.equal(smgr.charAt(au1234b, imgr.makeNumber(2)), stringVariable))
.implies(smgr.equal(stringVariable, b));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(u1234WOEscape, imgr.makeNumber(0)), u),
smgr.equal(smgr.charAt(u1234WOEscape, imgr.makeNumber(1)), num1)))
.isSatisfiable();
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(1)), u),
smgr.equal(smgr.charAt(au1234WOEscape, imgr.makeNumber(2)), num1)))
.isSatisfiable();
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(1)), u),
smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(2)), curlyOpen),
smgr.equal(smgr.charAt(au1234WOEscapeCurly, imgr.makeNumber(7)), curlyClose)))
.isSatisfiable();
// Check that the unicode is not treated as seperate chars
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(u1234, imgr.makeNumber(0)), smgr.makeString("\\")),
smgr.equal(smgr.charAt(u1234, imgr.makeNumber(1)), u),
smgr.equal(smgr.charAt(u1234, imgr.makeNumber(2)), num1)))
.isUnsatisfiable();
}
/**
* Same as {@link #testCharAtWithSpecialCharacters} but only with 2 Byte special chars as Z3 only
* supports those.
*/
@Test
public void testCharAtWithSpecialCharacters2Byte() throws SolverException, InterruptedException {
StringFormula num7 = smgr.makeString("7");
StringFormula u = smgr.makeString("u");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}");
StringFormula acurlyClose2BUnicodeb = smgr.makeString("a\\u{7D}b");
// Java needs a double {{ as the first one is needed as a escape char for the second, this is a
// workaround
String workaround = "au{7B}";
StringFormula acurlyOpen2BUnicodeWOEscapeCurly = smgr.makeString(workaround);
// StringFormula backSlash = smgr.makeString("\\");
StringFormula a = smgr.makeString("a");
StringFormula b = smgr.makeString("b");
StringFormula stringVariable = smgr.makeVariable("stringVariable");
// Curly braces unicode is treated as 1 char
assertThatFormula(imgr.equal(smgr.length(curlyOpen2BUnicode), imgr.makeNumber(1)))
.isSatisfiable();
assertThatFormula(imgr.equal(smgr.length(curlyClose2BUnicode), imgr.makeNumber(1)))
.isSatisfiable();
// check a}b
assertThatFormula(
smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(0)), stringVariable))
.implies(smgr.equal(stringVariable, a));
assertThatFormula(
smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(1)), stringVariable))
.implies(smgr.equal(stringVariable, curlyClose2BUnicode));
assertThatFormula(
smgr.equal(smgr.charAt(acurlyClose2BUnicodeb, imgr.makeNumber(2)), stringVariable))
.implies(smgr.equal(stringVariable, b));
// Check the unescaped version (missing backslash)
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(1)), u),
smgr.equal(
smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(2)),
curlyOpen2BUnicode),
smgr.equal(smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(3)), num7),
smgr.equal(
smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(4)),
smgr.makeString("B")),
smgr.equal(
smgr.charAt(acurlyOpen2BUnicodeWOEscapeCurly, imgr.makeNumber(5)),
curlyClose2BUnicode)))
.isSatisfiable();
}
@Test
public void testCharAtWithStringVariable() throws SolverException, InterruptedException {
StringFormula a = smgr.makeString("a");
StringFormula b = smgr.makeString("b");
StringFormula ab = smgr.makeString("ab");
StringFormula aa = smgr.makeString("aa");
StringFormula abc = smgr.makeString("abc");
StringFormula aabc = smgr.makeString("aabc");
StringFormula abcb = smgr.makeString("abcb");
StringFormula stringVariable = smgr.makeVariable("stringVariable");
assertThatFormula(smgr.equal(smgr.charAt(ab, imgr.makeNumber(0)), stringVariable))
.implies(smgr.equal(stringVariable, a));
assertThatFormula(smgr.equal(smgr.charAt(ab, imgr.makeNumber(1)), stringVariable))
.implies(smgr.equal(stringVariable, b));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(ab, imgr.makeNumber(0)), stringVariable),
smgr.equal(smgr.charAt(ab, imgr.makeNumber(1)), stringVariable)))
.isUnsatisfiable();
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(aa, imgr.makeNumber(0)), stringVariable),
smgr.equal(smgr.charAt(aa, imgr.makeNumber(1)), stringVariable)))
.implies(smgr.equal(stringVariable, a));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(1)), b),
imgr.equal(imgr.makeNumber(2), smgr.length(stringVariable))))
.implies(smgr.equal(stringVariable, ab));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(2)), b),
imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)),
smgr.suffix(abc, stringVariable)))
.implies(smgr.equal(stringVariable, aabc));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(3)), b),
imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)),
smgr.suffix(abc, stringVariable)))
.implies(smgr.equal(stringVariable, abcb));
assertThatFormula(
bmgr.and(
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(0)), a),
smgr.equal(smgr.charAt(stringVariable, imgr.makeNumber(3)), b),
imgr.equal(imgr.makeNumber(4), smgr.length(stringVariable)),
smgr.prefix(abc, stringVariable)))
.implies(smgr.equal(stringVariable, abcb));
}
@Test
public void testConstStringContains() throws SolverException, InterruptedException {
StringFormula empty = smgr.makeString("");
StringFormula a = smgr.makeString("a");
StringFormula aUppercase = smgr.makeString("A");
StringFormula bUppercase = smgr.makeString("B");
StringFormula b = smgr.makeString("b");
StringFormula bbbbbb = smgr.makeString("bbbbbb");
StringFormula bbbbbbb = smgr.makeString("bbbbbbb");
StringFormula abbbbbb = smgr.makeString("abbbbbb");
StringFormula aaaaaaaB = smgr.makeString("aaaaaaaB");
StringFormula abcAndSoOn = smgr.makeString("abcdefghijklmnopqrstuVwxyz");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}");
StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}");
StringFormula curlyClose2BUnicodeEncased = smgr.makeString("blabla\\u{7D}bla");
assertThatFormula(smgr.contains(empty, empty)).isSatisfiable();
assertThatFormula(smgr.contains(empty, a)).isUnsatisfiable();
assertThatFormula(smgr.contains(a, empty)).isSatisfiable();
assertThatFormula(smgr.contains(a, a)).isSatisfiable();
assertThatFormula(smgr.contains(a, aUppercase)).isUnsatisfiable();
assertThatFormula(smgr.contains(aUppercase, a)).isUnsatisfiable();
assertThatFormula(smgr.contains(a, b)).isUnsatisfiable();
assertThatFormula(smgr.contains(b, b)).isSatisfiable();
assertThatFormula(smgr.contains(abbbbbb, a)).isSatisfiable();
assertThatFormula(smgr.contains(abbbbbb, b)).isSatisfiable();
assertThatFormula(smgr.contains(abbbbbb, bbbbbb)).isSatisfiable();
assertThatFormula(smgr.contains(abbbbbb, bbbbbbb)).isUnsatisfiable();
assertThatFormula(smgr.contains(abbbbbb, aUppercase)).isUnsatisfiable();
assertThatFormula(smgr.contains(abbbbbb, aUppercase)).isUnsatisfiable();
assertThatFormula(smgr.contains(aaaaaaaB, a)).isSatisfiable();
assertThatFormula(smgr.contains(aaaaaaaB, b)).isUnsatisfiable();
assertThatFormula(smgr.contains(aaaaaaaB, bUppercase)).isSatisfiable();
assertThatFormula(smgr.contains(aaaaaaaB, curlyOpen2BUnicode)).isUnsatisfiable();
assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("xyz"))).isSatisfiable();
assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("Vwxyz"))).isSatisfiable();
assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("Vwxyza"))).isUnsatisfiable();
assertThatFormula(smgr.contains(abcAndSoOn, smgr.makeString("t Vwxyz"))).isUnsatisfiable();
assertThatFormula(smgr.contains(multipleCurlys2BUnicode, curlyOpen2BUnicode)).isSatisfiable();
assertThatFormula(smgr.contains(multipleCurlys2BUnicode, curlyClose2BUnicode)).isSatisfiable();
assertThatFormula(smgr.contains(curlyClose2BUnicodeEncased, curlyClose2BUnicode))
.isSatisfiable();
}
@Test
public void testStringVariableContains() throws SolverException, InterruptedException {
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
StringFormula empty = smgr.makeString("");
StringFormula bUppercase = smgr.makeString("B");
StringFormula ab = smgr.makeString("ab");
StringFormula bbbbbb = smgr.makeString("bbbbbb");
StringFormula abbbbbb = smgr.makeString("abbbbbb");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}");
assertThatFormula(
bmgr.and(smgr.contains(var1, empty), imgr.equal(imgr.makeNumber(0), smgr.length(var1))))
.implies(smgr.equal(var1, empty));
assertThatFormula(bmgr.and(smgr.contains(var1, var2), smgr.contains(var2, var1)))
.implies(smgr.equal(var1, var2));
// Unicode is treated as 1 char. So \\u{7B} is treated as { and the B inside is not contained!
assertThatFormula(
bmgr.and(
smgr.contains(var1, curlyOpen2BUnicode),
smgr.contains(var1, bUppercase),
imgr.equal(imgr.makeNumber(1), smgr.length(var1))))
.isUnsatisfiable();
// Same goes for the curly brackets used as escape sequence
assertThatFormula(
bmgr.and(
smgr.contains(var1, curlyOpen2BUnicode),
smgr.contains(var1, curlyClose2BUnicode),
imgr.equal(imgr.makeNumber(1), smgr.length(var1))))
.isUnsatisfiable();
assertThatFormula(
bmgr.and(
smgr.contains(var1, bbbbbb),
smgr.contains(var1, ab),
imgr.equal(imgr.makeNumber(7), smgr.length(var1))))
.implies(smgr.equal(var1, abbbbbb));
}
@Test
public void testStringContainsOtherVariable() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s runs endlessly on this task", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
StringFormula abUppercase = smgr.makeString("AB");
StringFormula ab = smgr.makeString("ab");
assertThatFormula(
bmgr.and(
smgr.contains(var1, ab),
smgr.contains(var2, abUppercase),
smgr.contains(var1, var2)))
.implies(smgr.contains(var1, abUppercase));
}
@Test
public void testConstStringIndexOf() throws SolverException, InterruptedException {
StringFormula empty = smgr.makeString("");
StringFormula a = smgr.makeString("a");
StringFormula aUppercase = smgr.makeString("A");
StringFormula b = smgr.makeString("b");
StringFormula ab = smgr.makeString("ab");
StringFormula bbbbbb = smgr.makeString("bbbbbb");
StringFormula bbbbbbb = smgr.makeString("bbbbbbb");
StringFormula abbbbbb = smgr.makeString("abbbbbb");
StringFormula abcAndSoOn = smgr.makeString("abcdefghijklmnopqrstuVwxyz");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}");
StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}");
// Z3 transforms this into {}, but CVC4 does not! CVC4 is on the side of the SMTLIB2 standard as
// far as I can see.
StringFormula curlys2BUnicodeWOEscape = smgr.makeString("\\u7B\\u7D");
IntegerFormula zero = imgr.makeNumber(0);
assertEqual(smgr.indexOf(empty, empty, zero), zero);
assertEqual(smgr.indexOf(a, empty, zero), zero);
assertEqual(smgr.indexOf(a, a, zero), zero);
assertEqual(smgr.indexOf(a, aUppercase, zero), imgr.makeNumber(-1));
assertEqual(smgr.indexOf(abbbbbb, a, zero), zero);
assertEqual(smgr.indexOf(abbbbbb, b, zero), imgr.makeNumber(1));
assertEqual(smgr.indexOf(abbbbbb, ab, zero), zero);
assertEqual(smgr.indexOf(abbbbbb, bbbbbb, zero), imgr.makeNumber(1));
assertEqual(smgr.indexOf(abbbbbb, bbbbbbb, zero), imgr.makeNumber(-1));
assertEqual(smgr.indexOf(abbbbbb, smgr.makeString("c"), zero), imgr.makeNumber(-1));
assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("z"), zero), imgr.makeNumber(25));
assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("V"), zero), imgr.makeNumber(21));
assertEqual(smgr.indexOf(abcAndSoOn, smgr.makeString("v"), zero), imgr.makeNumber(-1));
assertEqual(smgr.indexOf(multipleCurlys2BUnicode, curlyOpen2BUnicode, zero), zero);
assertEqual(
smgr.indexOf(multipleCurlys2BUnicode, curlyClose2BUnicode, zero), imgr.makeNumber(1));
// TODO: Z3 and CVC4 handle this differently!
// assertEqual(smgr.indexOf(multipleCurlys2BUnicode, curlys2BUnicodeWOEscape, zero), zero);
assertEqual(
smgr.indexOf(multipleCurlys2BUnicode, curlys2BUnicodeWOEscape, imgr.makeNumber(1)),
imgr.makeNumber(-1));
assertEqual(
smgr.indexOf(multipleCurlys2BUnicode, smgr.makeString("B"), zero), imgr.makeNumber(-1));
}
@Test
public void testStringVariableIndexOf() throws SolverException, InterruptedException {
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
IntegerFormula intVar = imgr.makeVariable("intVar");
StringFormula empty = smgr.makeString("");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
IntegerFormula zero = imgr.makeNumber(0);
// If the index of var2 is not -1, it is contained in var1.
assertThatFormula(
bmgr.and(
bmgr.not(imgr.equal(intVar, imgr.makeNumber(-1))),
imgr.equal(intVar, smgr.indexOf(var1, var2, zero))))
.implies(smgr.contains(var1, var2));
// If the index is less than 0 (only -1 possible) it is not contained.
assertThatFormula(
bmgr.and(
imgr.equal(intVar, smgr.indexOf(var1, var2, zero)), imgr.lessThan(intVar, zero)))
.implies(bmgr.not(smgr.contains(var1, var2)));
// If the index of var2 in var is >= 0 and vice versa, both contain each other.
assertThatFormula(
bmgr.and(
imgr.greaterOrEquals(smgr.indexOf(var1, var2, zero), zero),
imgr.greaterOrEquals(smgr.indexOf(var2, var1, zero), zero)))
.implies(bmgr.and(smgr.contains(var1, var2), smgr.contains(var2, var1)));
// If the are indices equal and one is >= 0 and the strings are not "", both are contained in
// each other and the chars at the position must be the same.
assertThatFormula(
bmgr.and(
imgr.equal(smgr.indexOf(var1, var2, zero), smgr.indexOf(var2, var1, zero)),
imgr.greaterOrEquals(smgr.indexOf(var1, var2, zero), zero),
bmgr.not(smgr.equal(empty, smgr.charAt(var1, smgr.indexOf(var1, var2, zero))))))
.implies(
bmgr.and(
smgr.contains(var1, var2),
smgr.contains(var2, var1),
smgr.equal(
smgr.charAt(var1, smgr.indexOf(var2, var1, zero)),
smgr.charAt(var1, smgr.indexOf(var1, var2, zero)))));
// If a String contains {, but not B, the index of B must be -1. (unicode of { contains B)
assertThatFormula(
bmgr.and(
smgr.contains(var1, curlyOpen2BUnicode),
bmgr.not(smgr.contains(var1, smgr.makeString("B")))))
.implies(
bmgr.and(
imgr.greaterOrEquals(smgr.indexOf(var1, curlyOpen2BUnicode, zero), zero),
imgr.equal(imgr.makeNumber(-1), smgr.indexOf(var1, smgr.makeString("B"), zero))));
}
@Test
public void testStringIndexOfWithSubStrings() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s runs endlessly on this task", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
StringFormula var1 = smgr.makeVariable("var1");
IntegerFormula zero = imgr.makeNumber(0);
// If the index of the string abba is 0, the index of the string bba is 1, and b is 1, and ba is
// 2
assertThatFormula(imgr.equal(zero, smgr.indexOf(var1, smgr.makeString("abba"), zero)))
.implies(
bmgr.and(
smgr.contains(var1, smgr.makeString("abba")),
imgr.equal(imgr.makeNumber(1), smgr.indexOf(var1, smgr.makeString("bba"), zero)),
imgr.equal(imgr.makeNumber(1), smgr.indexOf(var1, smgr.makeString("b"), zero)),
imgr.equal(imgr.makeNumber(2), smgr.indexOf(var1, smgr.makeString("ba"), zero))));
}
@Test
public void testStringPrefixImpliesPrefixIndexOf() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s runs endlessly on this task", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.Z3, Solvers.CVC4);
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
IntegerFormula zero = imgr.makeNumber(0);
// If a prefix (var2) is non empty, the length of the string (var1) has to be larger or equal to
// the prefix
// and the chars have to be the same for the lenth of the prefix, meaning the indexOf the prefix
// must be 0 in the string.
assertThatFormula(bmgr.and(imgr.greaterThan(smgr.length(var2), zero), smgr.prefix(var2, var1)))
.implies(
bmgr.and(
smgr.contains(var1, var2),
imgr.greaterOrEquals(smgr.length(var1), smgr.length(var2)),
imgr.equal(zero, smgr.indexOf(var1, var2, zero))));
}
@Test
public void testConstStringSubStrings() throws SolverException, InterruptedException {
StringFormula empty = smgr.makeString("");
StringFormula a = smgr.makeString("a");
StringFormula aUppercase = smgr.makeString("A");
StringFormula bUppercase = smgr.makeString("B");
StringFormula bbbbbb = smgr.makeString("bbbbbb");
StringFormula curlyOpen2BUnicode = smgr.makeString("\\u{7B}");
StringFormula curlyClose2BUnicode = smgr.makeString("\\u{7D}");
StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}");
IntegerFormula zero = imgr.makeNumber(0);
IntegerFormula one = imgr.makeNumber(1);
// Check empty string
assertEqual(smgr.substring(empty, zero, zero), empty);
// Check length 0 = empty string
assertEqual(smgr.substring(a, one, zero), empty);
// Check that it correctly recognized uppercase
assertDistinct(smgr.substring(a, zero, one), aUppercase);
assertDistinct(smgr.substring(aUppercase, zero, one), a);
assertDistinct(smgr.substring(bbbbbb, zero, one), bUppercase);
// Check smgr length interaction
assertEqual(smgr.substring(bbbbbb, zero, smgr.length(bbbbbb)), bbbbbb);
// Check unicode substrings
assertEqual(smgr.substring(multipleCurlys2BUnicode, zero, one), curlyOpen2BUnicode);
assertEqual(smgr.substring(multipleCurlys2BUnicode, one, one), curlyClose2BUnicode);
}
@Test
public void testConstStringAllPossibleSubStrings() throws SolverException, InterruptedException {
for (String wordString : WORDS) {
StringFormula word = smgr.makeString(wordString);
for (int j = 0; j < wordString.length(); j++) {
for (int k = j; k < wordString.length(); k++) {
// Loop through all combinations of substrings
// Note: String.substring uses begin index and end index (non-including) while SMT based
// substring uses length!
// Length = endIndex - beginIndex
String wordSubString = wordString.substring(j, k);
assertEqual(
smgr.substring(word, imgr.makeNumber(j), imgr.makeNumber(k - j)),
smgr.makeString(wordSubString));
}
}
}
}
@Test
public void testStringSubstringOutOfBounds() throws SolverException, InterruptedException {
StringFormula bbbbbb = smgr.makeString("bbbbbb");
StringFormula b = smgr.makeString("b");
StringFormula abbbbbb = smgr.makeString("abbbbbb");
StringFormula multipleCurlys2BUnicode = smgr.makeString("\\u{7B}\\u{7D}\\u{7B}\\u{7B}");
StringFormula multipleCurlys2BUnicodeFromIndex1 = smgr.makeString("\\u{7D}\\u{7B}\\u{7B}");
assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(0), imgr.makeNumber(10000)), abbbbbb);
assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(6), imgr.makeNumber(10000)), b);
assertEqual(smgr.substring(abbbbbb, imgr.makeNumber(1), imgr.makeNumber(10000)), bbbbbb);
assertEqual(
smgr.substring(multipleCurlys2BUnicode, imgr.makeNumber(1), imgr.makeNumber(10000)),
multipleCurlys2BUnicodeFromIndex1);
}
@Test
public void testStringVariablesSubstring() throws SolverException, InterruptedException {
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
IntegerFormula intVar1 = imgr.makeVariable("intVar1");
IntegerFormula intVar2 = imgr.makeVariable("intVar2");
// If a Prefix of a certain length exists, the substring over that equals the prefix
assertThatFormula(smgr.prefix(var2, var1))
.implies(smgr.equal(var2, smgr.substring(var1, imgr.makeNumber(0), smgr.length(var2))));
// Same with suffix
assertThatFormula(smgr.suffix(var2, var1))
.implies(
smgr.equal(
var2,
smgr.substring(
var1, imgr.subtract(smgr.length(var1), smgr.length(var2)), smgr.length(var2))));
// If a string has a char at a specified position, a substring beginning with the same index
// must have the same char, independent of the length of the substring.
// But its not really relevant to check out of bounds cases, hence the exclusion.
// So we test substring length 1 (== charAt) and larger
assertThatFormula(
bmgr.and(
imgr.greaterThan(intVar2, imgr.makeNumber(1)),
smgr.equal(var2, smgr.charAt(var1, intVar1)),
imgr.greaterThan(smgr.length(var1), intVar1)))
.implies(
smgr.equal(
var2, smgr.charAt(smgr.substring(var1, intVar1, intVar2), imgr.makeNumber(0))));
assertThatFormula(smgr.equal(var2, smgr.charAt(var1, intVar1)))
.implies(smgr.equal(var2, smgr.substring(var1, intVar1, imgr.makeNumber(1))));
}
@Test
public void testConstStringReplace() throws SolverException, InterruptedException {
for (int i = 0; i < WORDS.size(); i++) {
for (int j = 2; j < WORDS.size(); j++) {
String word1 = WORDS.get(j - 1);
String word2 = WORDS.get(j);
String word3 = WORDS.get(i);
StringFormula word1F = smgr.makeString(word1);
StringFormula word2F = smgr.makeString(word2);
StringFormula word3F = smgr.makeString(word3);
StringFormula result = smgr.makeString(word3.replaceFirst(word2, word1));
assertEqual(smgr.replace(word3F, word2F, word1F), result);
}
}
}
// Neither CVC4 nor Z3 can solve this!
@Ignore
@Test
public void testStringVariableReplacePrefix() throws SolverException, InterruptedException {
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
StringFormula var3 = smgr.makeVariable("var3");
StringFormula prefix = smgr.makeVariable("prefix");
// If var1 has a prefix, and you replace said prefix with var3 (saved in var2), the prefix of
// var2 is var3
assertThatFormula(
bmgr.and(
smgr.equal(var2, smgr.replace(var1, prefix, var3)),
smgr.prefix(prefix, var1),
bmgr.not(smgr.equal(prefix, var3)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
imgr.greaterThan(smgr.length(var3), imgr.makeNumber(0))))
.implies(bmgr.and(bmgr.not(smgr.equal(var1, var2)), smgr.prefix(var3, var2)));
assertThatFormula(
bmgr.and(
smgr.equal(var2, smgr.replace(var1, prefix, var3)),
smgr.prefix(prefix, var1),
bmgr.not(smgr.equal(prefix, var3))))
.implies(bmgr.and(smgr.prefix(var3, var2), bmgr.not(smgr.equal(var1, var2))));
}
@Test
public void testStringVariableReplaceSubstring() throws SolverException, InterruptedException {
// I couldn't find stronger constraints in the implication that don't run endlessly.....
StringFormula original = smgr.makeVariable("original");
StringFormula prefix = smgr.makeVariable("prefix");
StringFormula replacement = smgr.makeVariable("replacement");
StringFormula replaced = smgr.makeVariable("replaced");
// Set a prefix that does not contain the suffix substring, make sure that the substring that
// comes after the prefix is replaced
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, original),
imgr.equal(
smgr.length(prefix),
smgr.indexOf(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
imgr.makeNumber(0))),
imgr.greaterThan(smgr.length(original), smgr.length(prefix)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
imgr.greaterThan(
smgr.length(
smgr.substring(original, smgr.length(prefix), smgr.length(original))),
imgr.makeNumber(0)),
smgr.equal(
replaced,
smgr.replace(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
replacement))))
.implies(
smgr.equal(
replacement, smgr.substring(replaced, smgr.length(prefix), smgr.length(replaced))));
// In this version it is still possible that parts of the prefix and suffix together build the
// suffix, replacing parts of the prefix additionally to the implication above (or the
// replacement is empty)
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, original),
bmgr.not(smgr.contains(original, replacement)),
bmgr.not(
smgr.contains(
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
prefix)),
bmgr.not(
smgr.contains(
prefix,
smgr.substring(original, smgr.length(prefix), smgr.length(original)))),
imgr.greaterThan(smgr.length(original), smgr.length(prefix)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
smgr.equal(
replaced,
smgr.replace(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
replacement))))
.implies(smgr.contains(replacement, replacement));
// This version may have the original as a larger version of the prefix; prefix: a, original:
// aaa
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, original),
bmgr.not(smgr.contains(original, replacement)),
bmgr.not(
smgr.contains(
prefix,
smgr.substring(original, smgr.length(prefix), smgr.length(original)))),
imgr.greaterThan(smgr.length(original), smgr.length(prefix)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
smgr.equal(
replaced,
smgr.replace(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
replacement))))
.implies(smgr.contains(replacement, replacement));
// This version can contain the substring in the prefix!
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, original),
bmgr.not(smgr.contains(original, replacement)),
imgr.greaterThan(smgr.length(original), smgr.length(prefix)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
smgr.equal(
replaced,
smgr.replace(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
replacement))))
.implies(smgr.contains(replacement, replacement));
}
@Test
public void testStringVariableReplaceMiddle() throws SolverException, InterruptedException {
// TODO: either rework that this terminates, or remove
assume()
.withMessage("Solver %s runs endlessly on this task.", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.CVC4, Solvers.Z3);
StringFormula original = smgr.makeVariable("original");
StringFormula replacement = smgr.makeVariable("replacement");
StringFormula replaced = smgr.makeVariable("replaced");
StringFormula beginning = smgr.makeVariable("beginning");
StringFormula middle = smgr.makeVariable("middle");
StringFormula end = smgr.makeVariable("end");
// If beginning + middle + end (length of each > 0) get concatenated (in original), replacing
// beginning/middle/end
// with replacement (result = replaces; replacement > 0 and != the replaced) results in a
// string that is equal to the concat of the 2 remaining start strings and the replaced one
// replaced
// This is tested with 2 different implications, 1 that only checks whether or not the
// replacement is contained in the string and not in the original and vice verse for the
// replaced String
BooleanFormula formula =
bmgr.and(
smgr.equal(original, smgr.concat(beginning, middle, end)),
smgr.equal(replaced, smgr.replace(original, middle, replacement)),
bmgr.not(smgr.equal(middle, replacement)),
bmgr.not(smgr.equal(beginning, replacement)),
bmgr.not(smgr.equal(end, replacement)),
bmgr.not(smgr.equal(beginning, middle)),
imgr.greaterThan(smgr.length(middle), imgr.makeNumber(0)),
imgr.greaterThan(smgr.length(replacement), imgr.makeNumber(0)),
imgr.greaterThan(smgr.length(beginning), imgr.makeNumber(0)));
assertThatFormula(formula)
.implies(
bmgr.and(
bmgr.not(smgr.equal(original, replaced)), smgr.contains(replaced, replacement)));
assume()
.withMessage("Solver %s returns the initial formula.", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.CVC5);
// Same as above, but with concat instead of contains
assertThatFormula(formula)
.implies(
bmgr.and(
bmgr.not(smgr.equal(original, replaced)),
smgr.equal(replaced, smgr.concat(beginning, replacement, end))));
}
@Test
public void testStringVariableReplaceFront() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s runs endlessly on this task.", solverToUse())
.that(solverToUse())
.isNoneOf(Solvers.Z3, Solvers.CVC5);
StringFormula var1 = smgr.makeVariable("var1");
StringFormula var2 = smgr.makeVariable("var2");
StringFormula var3 = smgr.makeVariable("var3");
StringFormula var4 = smgr.makeVariable("var4");
StringFormula var5 = smgr.makeVariable("var5");
// If var1 and 2 get concated (in var4) such that var1 is in front, replacing var1 with var3
// (var5) results in a
// string that is equal to var3 + var2
// First with length constraints, second without
assertThatFormula(
bmgr.and(
smgr.equal(var4, smgr.concat(var1, var2)),
smgr.equal(var5, smgr.replace(var4, var1, var3)),
bmgr.not(smgr.equal(var1, var3)),
imgr.greaterThan(smgr.length(var1), imgr.makeNumber(0)),
imgr.greaterThan(smgr.length(var3), imgr.makeNumber(0))))
.implies(bmgr.and(bmgr.not(smgr.equal(var4, var5)), smgr.prefix(var3, var5)));
assertThatFormula(
bmgr.and(
smgr.equal(var4, smgr.concat(var1, var2)),
smgr.equal(var5, smgr.replace(var4, var1, var3)),
bmgr.not(smgr.equal(var1, var3))))
.implies(bmgr.and(bmgr.not(smgr.equal(var4, var5)), smgr.prefix(var3, var5)));
}
@Test
public void testConstStringReplaceAll() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support replaceAll()", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
for (int i = 0; i < WORDS.size(); i++) {
for (int j = 1; j < WORDS.size(); j++) {
String word1 = WORDS.get(i);
String word2 = WORDS.get(j);
String word3 = "replacement";
StringFormula word1F = smgr.makeString(word1);
StringFormula word2F = smgr.makeString(word2);
StringFormula word3F = smgr.makeString(word3);
StringFormula result = smgr.makeString(word3.replaceAll(word2, word1));
assertEqual(smgr.replaceAll(word3F, word2F, word1F), result);
}
}
}
/**
* Concat a String that consists of a String that is later replaces with replaceAll. The resulting
* String should consist of only concatinated versions of itself.
*/
@Test
public void testStringVariableReplaceAllConcatedString()
throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support replaceAll()", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
// 2 concats is the max number CVC4 supports without running endlessly
for (int numOfConcats = 0; numOfConcats < 3; numOfConcats++) {
StringFormula original = smgr.makeVariable("original");
StringFormula replacement = smgr.makeVariable("replacement");
StringFormula replaced = smgr.makeVariable("replaced");
StringFormula segment = smgr.makeVariable("segment");
StringFormula[] concatSegments = new StringFormula[numOfConcats];
StringFormula[] concatReplacements = new StringFormula[numOfConcats];
for (int i = 0; i < numOfConcats; i++) {
concatSegments[i] = segment;
concatReplacements[i] = replacement;
}
BooleanFormula formula =
bmgr.and(
smgr.equal(original, smgr.concat(concatSegments)),
smgr.equal(replaced, smgr.replaceAll(original, segment, replacement)),
bmgr.not(smgr.equal(segment, replacement)),
imgr.greaterThan(smgr.length(segment), imgr.makeNumber(0)),
imgr.greaterThan(smgr.length(replacement), imgr.makeNumber(0)));
assertThatFormula(formula).implies(smgr.equal(replaced, smgr.concat(concatReplacements)));
}
}
@Test
public void testStringVariableReplaceAllSubstring() throws SolverException, InterruptedException {
assume()
.withMessage("Solver %s does not support replaceAll()", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.Z3);
// I couldn't find stronger constraints in the implication that don't run endlessly.....
StringFormula original = smgr.makeVariable("original");
StringFormula prefix = smgr.makeVariable("prefix");
StringFormula replacement = smgr.makeVariable("replacement");
StringFormula replaced = smgr.makeVariable("replaced");
// Set a prefix that does not contain the suffix substring, make sure that the substring that
// comes after the prefix is replaced
assertThatFormula(
bmgr.and(
smgr.prefix(prefix, original),
imgr.equal(
smgr.length(prefix),
smgr.indexOf(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
imgr.makeNumber(0))),
imgr.greaterThan(smgr.length(original), smgr.length(prefix)),
imgr.greaterThan(smgr.length(prefix), imgr.makeNumber(0)),
imgr.greaterThan(
smgr.length(
smgr.substring(original, smgr.length(prefix), smgr.length(original))),
imgr.makeNumber(0)),
smgr.equal(
replaced,
smgr.replaceAll(
original,
smgr.substring(original, smgr.length(prefix), smgr.length(original)),
replacement))))
.implies(
smgr.equal(
replacement, smgr.substring(replaced, smgr.length(prefix), smgr.length(replaced))));
}
@Test
public void testStringConcatWUnicode() throws SolverException, InterruptedException {
StringFormula backslash = smgr.makeString("\\");
StringFormula u = smgr.makeString("u");
StringFormula curlyOpen = smgr.makeString("\\u{7B}");
StringFormula sevenB = smgr.makeString("7B");
StringFormula curlyClose = smgr.makeString("\\u{7D}");
StringFormula concat = smgr.concat(backslash, u, curlyOpen, sevenB, curlyClose);
StringFormula complete = smgr.makeString("\\u{7B}");
// Concatting parts of unicode does not result in the unicode char!
assertDistinct(concat, complete);
}
@Test
public void testStringSimpleRegex() {
// TODO
}
@Test
public void testVisitorForStringConstants() {
BooleanFormula eq =
bmgr.and(
smgr.equal(smgr.makeString("x"), smgr.makeString("xx")),
smgr.lessThan(smgr.makeString("y"), smgr.makeString("yy")));
Map<String, Formula> freeVars = mgr.extractVariables(eq);
assertThat(freeVars).isEmpty();
Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(eq);
assertThat(freeVarsAndUfs).isEmpty();
}
@Test
public void testVisitorForRegexConstants() {
RegexFormula concat = smgr.concat(smgr.makeRegex("x"), smgr.makeRegex("xx"));
Map<String, Formula> freeVars = mgr.extractVariables(concat);
assertThat(freeVars).isEmpty();
Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(concat);
assertThat(freeVarsAndUfs).isEmpty();
}
@Test
public void testVisitorForStringSymbols() {
BooleanFormula eq = smgr.equal(smgr.makeVariable("x"), smgr.makeString("xx"));
Map<String, Formula> freeVars = mgr.extractVariables(eq);
assertThat(freeVars).containsExactly("x", smgr.makeVariable("x"));
Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(eq);
assertThat(freeVarsAndUfs).containsExactly("x", smgr.makeVariable("x"));
}
@Test
public void testVisitorForRegexSymbols() {
BooleanFormula in = smgr.in(smgr.makeVariable("x"), smgr.makeRegex("xx"));
Map<String, Formula> freeVars = mgr.extractVariables(in);
assertThat(freeVars).containsExactly("x", smgr.makeVariable("x"));
Map<String, Formula> freeVarsAndUfs = mgr.extractVariablesAndUFs(in);
assertThat(freeVarsAndUfs).containsExactly("x", smgr.makeVariable("x"));
}
}
| 72,824 | 43.029625 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/TimeoutTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static org.junit.Assert.assertThrows;
import com.google.common.truth.TruthJUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Tactic;
/** Check that timeout is handled gracefully. */
@RunWith(Parameterized.class)
public class TimeoutTest extends SolverBasedTest0 {
private static final int TIMOUT_MILLISECONDS = 10000;
private static final int[] DELAYS = {1, 5, 10, 20, 50, 100};
@Parameters(name = "{0} with delay {1}")
public static List<Object[]> getAllSolversAndDelays() {
List<Object[]> lst = new ArrayList<>();
for (Solvers solver : Solvers.values()) {
for (int delay : DELAYS) {
lst.add(new Object[] {solver, delay});
}
}
return lst;
}
@Parameter(0)
public Solvers solver;
@Parameter(1)
public int delay;
@Override
protected Solvers solverToUse() {
return solver;
}
@Test
@SuppressWarnings("CheckReturnValue")
public void testTacticTimeout() {
TruthJUnit.assume()
.withMessage("Only Z3 has native tactics")
.that(solverToUse())
.isEqualTo(Solvers.Z3);
Fuzzer fuzzer = new Fuzzer(mgr, new Random(0));
String msg = "ShutdownRequest";
BooleanFormula test = fuzzer.fuzz(20, 3);
shutdownManager.requestShutdown(msg);
assertThrows(msg, InterruptedException.class, () -> mgr.applyTactic(test, Tactic.NNF));
}
@Test(timeout = TIMOUT_MILLISECONDS)
public void testProverTimeoutInt() throws InterruptedException {
requireIntegers();
TruthJUnit.assume()
.withMessage(solverToUse() + " does not support interruption")
.that(solverToUse())
.isNoneOf(Solvers.PRINCESS, Solvers.BOOLECTOR, Solvers.CVC5);
testBasicProverTimeoutInt(() -> context.newProverEnvironment());
}
@Test(timeout = TIMOUT_MILLISECONDS)
public void testProverTimeoutBv() throws InterruptedException {
requireBitvectors();
TruthJUnit.assume()
.withMessage(solverToUse() + " does not support interruption")
.that(solverToUse())
.isNoneOf(Solvers.PRINCESS, Solvers.CVC5);
testBasicProverTimeoutBv(() -> context.newProverEnvironment());
}
@Test(timeout = TIMOUT_MILLISECONDS)
public void testInterpolationProverTimeout() throws InterruptedException {
requireInterpolation();
requireIntegers();
TruthJUnit.assume()
.withMessage(solverToUse() + " does not support interruption")
.that(solverToUse())
.isNoneOf(Solvers.PRINCESS, Solvers.BOOLECTOR, Solvers.CVC5);
testBasicProverTimeoutInt(() -> context.newProverEnvironmentWithInterpolation());
}
@Test(timeout = TIMOUT_MILLISECONDS)
public void testOptimizationProverTimeout() throws InterruptedException {
requireOptimization();
requireIntegers();
testBasicProverTimeoutInt(() -> context.newOptimizationProverEnvironment());
}
private void testBasicProverTimeoutInt(Supplier<BasicProverEnvironment<?>> proverConstructor)
throws InterruptedException {
HardIntegerFormulaGenerator gen = new HardIntegerFormulaGenerator(imgr, bmgr);
testBasicProverTimeout(proverConstructor, gen.generate(100));
}
private void testBasicProverTimeoutBv(Supplier<BasicProverEnvironment<?>> proverConstructor)
throws InterruptedException {
HardBitvectorFormulaGenerator gen = new HardBitvectorFormulaGenerator(bvmgr, bmgr);
testBasicProverTimeout(proverConstructor, gen.generate(100));
}
@SuppressWarnings("CheckReturnValue")
private void testBasicProverTimeout(
Supplier<BasicProverEnvironment<?>> proverConstructor, BooleanFormula instance)
throws InterruptedException {
Thread t =
new Thread(
() -> {
try {
Thread.sleep(delay);
shutdownManager.requestShutdown("Shutdown Request");
} catch (InterruptedException pE) {
throw new UnsupportedOperationException("Unexpected interrupt");
}
});
try (BasicProverEnvironment<?> pe = proverConstructor.get()) {
pe.push(instance);
t.start();
assertThrows(InterruptedException.class, pe::isUnsat);
}
}
}
| 4,866 | 33.034965 | 95 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/TranslateFormulaTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.test.BooleanFormulaSubject.assertUsing;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.ShutdownManager;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.java_smt.SolverContextFactory;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.IntegerFormulaManager;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverContext;
import org.sosy_lab.java_smt.api.SolverException;
/** Testing formula serialization. */
@RunWith(Parameterized.class)
public class TranslateFormulaTest {
private final LogManager logger = LogManager.createTestLogManager();
private SolverContext from;
private SolverContext to;
private FormulaManager managerFrom;
private FormulaManager managerTo;
@Parameter(0)
public Solvers translateFrom;
@Parameter(1)
public Solvers translateTo;
@Parameters(name = "{index}: {0} --> {1}")
public static List<Object[]> getSolverCombinations() {
List<Solvers> solvers = Arrays.asList(Solvers.values());
return Lists.transform(Lists.cartesianProduct(solvers, solvers), List::toArray);
}
@Before
public void initSolvers() throws InvalidConfigurationException {
Configuration empty = Configuration.builder().build();
SolverContextFactory factory =
new SolverContextFactory(empty, logger, ShutdownManager.create().getNotifier());
try {
from = factory.generateContext(translateFrom);
to = factory.generateContext(translateTo);
} catch (InvalidConfigurationException e) {
assume()
.withMessage(e.getMessage())
.that(e)
.hasCauseThat()
.isNotInstanceOf(UnsatisfiedLinkError.class);
throw e;
}
managerFrom = from.getFormulaManager();
managerTo = to.getFormulaManager();
}
@After
public void close() {
if (from != null) {
from.close();
}
if (to != null) {
to.close();
}
}
private void requireParserTo() {
assume()
.withMessage("Solver %s does not support parsing formulae", translateTo)
.that(translateTo)
.isNoneOf(Solvers.CVC4, Solvers.BOOLECTOR, Solvers.YICES2, Solvers.CVC5);
}
private void requireParserFrom() {
assume()
.withMessage("Solver %s does not support parsing formulae", translateFrom)
.that(translateFrom)
.isNoneOf(Solvers.CVC4, Solvers.BOOLECTOR, Solvers.YICES2, Solvers.CVC5);
}
private void requireIntegers() {
assume()
.withMessage("Solver %s does not support integer theory", translateFrom)
.that(translateFrom)
.isNotEqualTo(Solvers.BOOLECTOR);
}
@Test
public void testDumpingAndParsing() throws SolverException, InterruptedException {
requireParserTo();
BooleanFormula input = createTestFormula(managerFrom);
String out = managerFrom.dumpFormula(input).toString();
BooleanFormula parsed = managerTo.parse(out);
assertUsing(to).that(createTestFormula(managerTo)).isEquivalentTo(parsed);
}
@Test
public void testTranslating() throws SolverException, InterruptedException {
requireParserTo();
BooleanFormula inputFrom = createTestFormula(managerFrom);
BooleanFormula inputTo = createTestFormula(managerTo);
BooleanFormula translatedInput = managerTo.translateFrom(inputFrom, managerFrom);
assertUsing(to).that(inputTo).isEquivalentTo(translatedInput);
}
@Test
public void testTranslatingForIContextdentity() throws SolverException, InterruptedException {
assume().that(translateTo).isEqualTo(translateFrom);
FormulaManager manager = managerFrom;
BooleanFormula inputFrom = createTestFormula(manager);
BooleanFormula inputTo = createTestFormula(manager);
BooleanFormula translatedInput = manager.translateFrom(inputFrom, manager);
assertUsing(to).that(inputTo).isEquivalentTo(translatedInput);
}
@Test
public void testTranslatingForContextSibling() throws SolverException, InterruptedException {
assume().that(translateTo).isEqualTo(translateFrom);
assume()
.withMessage("Solver does not support shared terms or dump/parse")
.that(translateTo)
.isNoneOf(Solvers.CVC4, Solvers.CVC5, Solvers.YICES2);
BooleanFormula inputFrom = createTestFormula(managerFrom);
BooleanFormula inputTo = createTestFormula(managerTo);
BooleanFormula translatedInput = managerTo.translateFrom(inputFrom, managerFrom);
assertUsing(to).that(inputTo).isEquivalentTo(translatedInput);
}
@Test
public void testTranslatingAndReverse() throws SolverException, InterruptedException {
requireParserTo();
requireParserFrom();
BooleanFormula inputFrom = createTestFormula(managerFrom);
BooleanFormula translatedInput = managerTo.translateFrom(inputFrom, managerFrom);
BooleanFormula translatedReverseInput = managerFrom.translateFrom(translatedInput, managerTo);
assertUsing(from).that(inputFrom).isEquivalentTo(translatedReverseInput);
}
private BooleanFormula createTestFormula(FormulaManager mgr) {
requireIntegers();
BooleanFormulaManager bfmgr = mgr.getBooleanFormulaManager();
IntegerFormulaManager ifmgr = mgr.getIntegerFormulaManager();
IntegerFormula x = ifmgr.makeVariable("x");
IntegerFormula y = ifmgr.makeVariable("y");
IntegerFormula z = ifmgr.makeVariable("z");
BooleanFormula t =
bfmgr.and(
bfmgr.or(ifmgr.equal(x, y), ifmgr.equal(x, ifmgr.makeNumber(2))),
bfmgr.or(ifmgr.equal(y, z), ifmgr.equal(z, ifmgr.makeNumber(10))));
return t;
}
}
| 6,541 | 33.431579 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/UFManagerTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.Truth;
import java.util.List;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.visitors.ExpectedFormulaVisitor;
public class UFManagerTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private static final ImmutableList<String> VALID_NAMES = ImmutableList.of("Func", "(Func)");
@Test
public void testDeclareAndCallUFWithInt() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula value = imgr.makeNumber(1234);
for (String name : VALID_NAMES) {
Formula f =
fmgr.declareAndCallUF(
name, FormulaType.IntegerType, ImmutableList.of(imgr.makeNumber(1)));
FunctionDeclaration<?> declaration = getDeclaration(f);
Truth.assertThat(declaration.getName()).isEqualTo(name);
Formula f2 = mgr.makeApplication(declaration, imgr.makeNumber(1));
Truth.assertThat(f2).isEqualTo(f);
assertThatFormula(imgr.equal(value, x))
.implies(
imgr.equal(
(IntegerFormula) mgr.makeApplication(declaration, value),
(IntegerFormula) mgr.makeApplication(declaration, x)));
}
}
@Test
public void testDeclareAndCallUFWithRational() throws SolverException, InterruptedException {
requireRationals();
RationalFormula x = rmgr.makeVariable("x");
RationalFormula value = rmgr.makeNumber(0.5);
for (String name : VALID_NAMES) {
Formula f =
fmgr.declareAndCallUF(
name, FormulaType.RationalType, ImmutableList.of(rmgr.makeNumber(1.5)));
FunctionDeclaration<?> declaration = getDeclaration(f);
Truth.assertThat(declaration.getName()).isEqualTo(name);
Formula f2 = mgr.makeApplication(declaration, rmgr.makeNumber(1.5));
Truth.assertThat(f2).isEqualTo(f);
assertThatFormula(rmgr.equal(value, x))
.implies(
rmgr.equal(
(RationalFormula) mgr.makeApplication(declaration, value),
(RationalFormula) mgr.makeApplication(declaration, x)));
}
}
@Test
public void testDeclareAndCallUFWithIntAndRational()
throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula value = imgr.makeNumber(1234);
for (String name : VALID_NAMES) {
Formula f =
fmgr.declareAndCallUF(
name, FormulaType.RationalType, ImmutableList.of(rmgr.makeNumber(1)));
FunctionDeclaration<?> declaration = getDeclaration(f);
Truth.assertThat(declaration.getName()).isEqualTo(name);
Formula f2 = mgr.makeApplication(declaration, imgr.makeNumber(1));
switch (solverToUse()) {
case CVC5:
case SMTINTERPOL:
case Z3:
// some solvers have an explicit cast for the parameter
Truth.assertThat(f2).isNotEqualTo(f);
List<Formula> args = getArguments(f2);
Truth.assertThat(args).hasSize(1);
FunctionDeclaration<?> cast = getDeclaration(args.get(0));
Truth.assertThat(cast.getName()).isEqualTo("to_real");
Truth.assertThat(cast.getKind()).isEqualTo(FunctionDeclarationKind.TO_REAL);
List<Formula> castedValues = getArguments(args.get(0));
Truth.assertThat(castedValues).hasSize(1);
Truth.assertThat(castedValues.get(0).toString()).isEqualTo("1");
break;
default:
Truth.assertThat(f2).isEqualTo(f);
}
assertThatFormula(rmgr.equal(value, x))
.implies(
rmgr.equal(
(RationalFormula) mgr.makeApplication(declaration, value),
(RationalFormula) mgr.makeApplication(declaration, x)));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesIntVsRational() {
requireIntegers();
requireRationals();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(name, FormulaType.IntegerType, ImmutableList.of(FormulaType.IntegerType));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, rmgr.makeNumber(2.88)));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, rmgr.makeNumber(0.001)));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, rmgr.makeNumber(-2.88)));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesIntVsBool() {
requireIntegers();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(name, FormulaType.IntegerType, ImmutableList.of(FormulaType.IntegerType));
assertThrows(
IllegalArgumentException.class, () -> mgr.makeApplication(declaration, bmgr.makeTrue()));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesBoolVsInt() {
requireIntegers();
requireBooleanArgument();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(name, FormulaType.IntegerType, ImmutableList.of(FormulaType.BooleanType));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, imgr.makeNumber(1)));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesBV4VsBool() {
requireBitvectors();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(
name,
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(FormulaType.getBitvectorTypeWithSize(4)));
assertThrows(
IllegalArgumentException.class, () -> mgr.makeApplication(declaration, bmgr.makeTrue()));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, bvmgr.makeBitvector(8, 8)));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesBV4VsInt() {
requireBitvectors();
requireIntegers();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(
name,
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(FormulaType.getBitvectorTypeWithSize(4)));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, imgr.makeNumber(123)));
}
}
@Test
public void testDeclareAndCallUFWithIncompatibleTypesBV4VsRational() {
requireBitvectors();
requireRationals();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(
name,
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(FormulaType.getBitvectorTypeWithSize(4)));
assertThrows(
IllegalArgumentException.class,
() -> mgr.makeApplication(declaration, rmgr.makeNumber(1.234)));
}
}
@Test
public void testDeclareAndCallUFWithBooleanAndBVTypes() {
requireBitvectors();
for (String name : VALID_NAMES) {
FunctionDeclaration<?> declaration =
fmgr.declareUF(
name,
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(FormulaType.getBitvectorTypeWithSize(1)));
assertThrows(
IllegalArgumentException.class, () -> mgr.makeApplication(declaration, bmgr.makeTrue()));
}
}
@SuppressWarnings("CheckReturnValue")
@Test
public void testDeclareAndCallUFWithIntWithUnsupportedName() {
requireIntegers();
assertThrows(
IllegalArgumentException.class,
() ->
fmgr.declareAndCallUF(
"|Func|", FormulaType.IntegerType, ImmutableList.of(imgr.makeNumber(1))));
assertThrows(
IllegalArgumentException.class,
() ->
fmgr.declareUF(
"|Func|", FormulaType.IntegerType, ImmutableList.of(FormulaType.IntegerType)));
}
@Test
public void testDeclareAndCallUFWithBv() {
requireBitvectors();
for (String name : VALID_NAMES) {
Formula f =
fmgr.declareAndCallUF(
name,
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(bvmgr.makeBitvector(4, 1)));
FunctionDeclaration<?> declaration = getDeclaration(f);
Truth.assertThat(declaration.getName()).isEqualTo(name);
Formula f2 = mgr.makeApplication(declaration, bvmgr.makeBitvector(4, 1));
Truth.assertThat(f2).isEqualTo(f);
}
}
@Test
@SuppressWarnings("CheckReturnValue")
public void testDeclareAndCallUFWithBvWithUnsupportedName() {
requireBitvectors();
assertThrows(
IllegalArgumentException.class,
() ->
fmgr.declareAndCallUF(
"|Func|",
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(bvmgr.makeBitvector(4, 1))));
assertThrows(
IllegalArgumentException.class,
() ->
fmgr.declareUF(
"|Func|",
FormulaType.getBitvectorTypeWithSize(4),
ImmutableList.of(FormulaType.getBitvectorTypeWithSize(4))));
}
@Test
public void testDeclareAndCallUFWithTypedArgs() {
requireBooleanArgument();
createAndCallUF("fooBool1", FormulaType.BooleanType, bmgr.makeTrue());
createAndCallUF("fooBool2", FormulaType.BooleanType, bmgr.makeTrue(), bmgr.makeTrue());
createAndCallUF(
"fooBool3", FormulaType.IntegerType, bmgr.makeTrue(), bmgr.makeTrue(), bmgr.makeTrue());
createAndCallUF("fooInt1", FormulaType.IntegerType, imgr.makeNumber(2));
createAndCallUF("fooInt2", FormulaType.IntegerType, imgr.makeNumber(1), imgr.makeNumber(2));
createAndCallUF(
"fooInt3",
FormulaType.BooleanType,
imgr.makeNumber(1),
imgr.makeNumber(2),
imgr.makeNumber(3));
createAndCallUF("fooMixed1", FormulaType.IntegerType, bmgr.makeTrue(), imgr.makeNumber(2));
createAndCallUF(
"fooMixed2", FormulaType.IntegerType, bmgr.makeTrue(), bmgr.makeTrue(), imgr.makeNumber(2));
createAndCallUF(
"fooMixed3", FormulaType.BooleanType, bmgr.makeTrue(), imgr.makeNumber(2), bmgr.makeTrue());
}
@Test
public void testDeclareAndCallUFWithRationalArgs() {
requireRationals();
createAndCallUF("fooRat1", FormulaType.RationalType, rmgr.makeNumber(2.5));
createAndCallUF("fooRat2", FormulaType.IntegerType, rmgr.makeNumber(1.5), rmgr.makeNumber(2.5));
requireBooleanArgument();
createAndCallUF(
"fooMixed3",
FormulaType.BooleanType,
bmgr.makeTrue(),
imgr.makeNumber(2),
rmgr.makeNumber(3.33));
}
@Test
public void testDeclareAndCallUFWithBVArgs() {
requireBitvectors();
createAndCallUF("fooBV1", FormulaType.getBitvectorTypeWithSize(5), bvmgr.makeBitvector(3, 3L));
requireBooleanArgument();
createAndCallUF(
"fooMixedBV1",
FormulaType.getBitvectorTypeWithSize(5),
bmgr.makeTrue(),
imgr.makeNumber(2),
bvmgr.makeBitvector(3, 3L));
createAndCallUF(
"fooMixedBV2",
FormulaType.BooleanType,
bmgr.makeTrue(),
imgr.makeNumber(2),
bvmgr.makeBitvector(3, 3L));
}
private void requireBooleanArgument() {
assume()
.withMessage("Solver %s does not support boolean arguments", solverToUse())
.that(solver)
.isNoneOf(Solvers.MATHSAT5, Solvers.PRINCESS);
}
/** utility method: create an UF from given arguments and return type and calls it. */
private void createAndCallUF(
String name, FormulaType<? extends Formula> retType, Formula... args) {
Formula f = fmgr.declareAndCallUF(name, retType, args);
FunctionDeclaration<?> declaration = getDeclaration(f);
Truth.assertThat(declaration.getName()).isEqualTo(name);
Formula f2 = mgr.makeApplication(declaration, args);
Truth.assertThat(f2).isEqualTo(f);
}
private FunctionDeclaration<?> getDeclaration(Formula pFormula) {
assume()
.withMessage("Solver %s does not support visiters", solverToUse())
.that(solver)
.isNotEqualTo(Solvers.BOOLECTOR);
return mgr.visit(
pFormula,
new ExpectedFormulaVisitor<>() {
@Override
public FunctionDeclaration<?> visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
return functionDeclaration;
}
});
}
private List<Formula> getArguments(Formula pFormula) {
assume()
.withMessage("Solver %s does not support visiters", solverToUse())
.that(solver)
.isNotEqualTo(Solvers.BOOLECTOR);
return mgr.visit(
pFormula,
new ExpectedFormulaVisitor<>() {
@Override
public List<Formula> visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) {
return args;
}
});
}
}
| 14,029 | 34.251256 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/UfEliminationTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.Truth;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.utils.SolverUtils;
import org.sosy_lab.java_smt.utils.UfElimination;
import org.sosy_lab.java_smt.utils.UfElimination.Result;
public class UfEliminationTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
private UfElimination ackermannization;
@Before
public void setUp() {
ackermannization = SolverUtils.ufElimination(mgr);
}
@Test
public void simpleTest() throws SolverException, InterruptedException {
requireIntegers();
// f := uf(v1, v3) XOR uf(v2, v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula f = bmgr.xor(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4);
BooleanFormula withOutUfs = ackermannization.eliminateUfs(f);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf");
Truth.assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void nestedUfs() throws SolverException, InterruptedException {
requireIntegers();
// f := uf2(uf1(v1, v2), v3) XOR uf2(uf1(v2, v1), v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
FunctionDeclaration<IntegerFormula> uf1Decl =
fmgr.declareUF("uf1", IntegerType, IntegerType, IntegerType);
Formula uf1a = fmgr.callUF(uf1Decl, variable1, variable2);
Formula uf1b = fmgr.callUF(uf1Decl, variable2, variable1);
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf2", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, uf1a, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, uf1b, variable4);
BooleanFormula f = bmgr.xor(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4);
BooleanFormula withOutUfs = ackermannization.eliminateUfs(f);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf1");
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf2");
Truth.assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void nestedUfs2() throws SolverException, InterruptedException {
requireIntegers();
// f := uf2(uf1(v1, uf2(v3, v6)), v3) < uf2(uf1(v2, uf2(v4, v5)), v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
IntegerFormula variable5 = imgr.makeVariable("variable5");
IntegerFormula variable6 = imgr.makeVariable("variable6");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
BooleanFormula v5EqualsV6 = imgr.equal(variable5, variable6);
FunctionDeclaration<IntegerFormula> uf1Decl =
fmgr.declareUF("uf1", IntegerType, IntegerType, IntegerType);
FunctionDeclaration<IntegerFormula> uf2Decl =
fmgr.declareUF("uf2", IntegerType, IntegerType, IntegerType);
Formula uf2a = fmgr.callUF(uf2Decl, variable1, variable2);
Formula uf2b = fmgr.callUF(uf2Decl, variable1, variable2);
Formula uf1a = fmgr.callUF(uf1Decl, variable1, uf2a);
Formula uf1b = fmgr.callUF(uf1Decl, variable2, uf2b);
IntegerFormula f1 = fmgr.callUF(uf2Decl, uf1a, variable3);
IntegerFormula f2 = fmgr.callUF(uf2Decl, uf1b, variable4);
BooleanFormula f = imgr.lessThan(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4, v5EqualsV6);
BooleanFormula withOutUfs = ackermannization.eliminateUfs(f);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf1");
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf2");
Truth.assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void nestedUfs3() throws SolverException, InterruptedException {
requireIntegers();
// f := uf(v1) < uf(v2)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
FunctionDeclaration<IntegerFormula> ufDecl = fmgr.declareUF("uf", IntegerType, IntegerType);
IntegerFormula f1 = fmgr.callUF(ufDecl, variable1);
IntegerFormula f2 = fmgr.callUF(ufDecl, variable2);
BooleanFormula f = imgr.lessThan(f1, f2);
BooleanFormula argsEqual = imgr.equal(variable1, variable2);
BooleanFormula withOutUfs = ackermannization.eliminateUfs(f);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf1");
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf2");
Truth.assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void twoFormulasTest() throws SolverException, InterruptedException {
// See FormulaManagerTest.testEmptySubstitution(), FormulaManagerTest.testNoSubstitution()
requireIntegers();
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
// f := uf(v1, v3) XOR uf(v2, v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
BooleanFormula v1EqualsV2 = imgr.equal(variable1, variable2);
BooleanFormula v3EqualsV4 = imgr.equal(variable3, variable4);
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula f = bmgr.xor(f1, f2);
BooleanFormula argsEqual = bmgr.and(v1EqualsV2, v3EqualsV4);
Result result1 = ackermannization.eliminateUfs(f1, Result.empty(mgr));
BooleanFormula withOutUfs1 = result1.getFormula();
Result result2 = ackermannization.eliminateUfs(f2, result1);
BooleanFormula withOutUfs2 = result2.getFormula();
BooleanFormula geConstraints = result2.getConstraints();
BooleanFormula withOutUfs = bmgr.and(bmgr.xor(withOutUfs1, withOutUfs2), geConstraints);
assertThatFormula(f).isSatisfiable(); // sanity check
assertThatFormula(withOutUfs).isSatisfiable();
assertThatFormula(bmgr.and(argsEqual, f)).isUnsatisfiable(); // sanity check
assertThatFormula(bmgr.and(argsEqual, withOutUfs)).isUnsatisfiable();
// check that UFs were really eliminated
Map<String, Formula> variablesAndUFs = mgr.extractVariablesAndUFs(withOutUfs);
Map<String, Formula> variables = mgr.extractVariables(withOutUfs);
Truth.assertThat(variablesAndUFs).doesNotContainKey("uf");
Truth.assertThat(variablesAndUFs).isEqualTo(variables);
}
@Test
public void quantifierTest() {
requireQuantifiers();
requireIntegers();
// f := exists v1,v2v,v3,v4 : uf(v1, v3) == uf(v2, v4)
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula f =
qmgr.exists(
ImmutableList.of(variable1, variable2, variable3, variable4), bmgr.equivalence(f1, f2));
try {
ackermannization.eliminateUfs(f);
assert_().fail();
} catch (IllegalArgumentException expected) {
}
}
@Test
public void substitutionTest() throws SolverException, InterruptedException {
requireIntegers();
// f := uf(v1, v3) \/ NOT(uf(v2, v4)))
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> ufDecl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(ufDecl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(ufDecl, variable2, variable4);
BooleanFormula f = bmgr.or(f1, bmgr.not(f2));
Result withOutUfs = ackermannization.eliminateUfs(f, Result.empty(mgr));
Map<Formula, Formula> substitution = withOutUfs.getSubstitution();
Truth.assertThat(substitution).hasSize(2);
BiMap<Formula, Formula> inverseSubstitution = HashBiMap.create(substitution).inverse();
BooleanFormula revertedSubstitution =
mgr.substitute(withOutUfs.getFormula(), inverseSubstitution);
assertThatFormula(f).isEquivalentTo(revertedSubstitution);
}
}
| 12,591 | 44.789091 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/VariableNamesEscaperTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.Lists;
import java.util.List;
import org.junit.Test;
/** inherits many tests from {@link VariableNamesTest}. */
public class VariableNamesEscaperTest extends VariableNamesTest {
@Override
boolean allowInvalidNames() {
return false;
}
@Override
protected List<String> getAllNames() {
return Lists.transform(super.getAllNames(), mgr::escape);
}
@Test
public void testEscapeUnescape() {
for (String var : getAllNames()) {
assertThat(mgr.unescape(mgr.escape(var))).isEqualTo(var);
assertThat(mgr.unescape(mgr.unescape(mgr.escape(mgr.escape(var))))).isEqualTo(var);
}
}
@Test
public void testDoubleEscapeUnescape() {
for (String var : getAllNames()) {
assertThat(mgr.unescape(mgr.escape(var))).isEqualTo(var);
assertThat(mgr.unescape(mgr.unescape(mgr.escape(mgr.escape(var))))).isEqualTo(var);
}
}
}
| 1,239 | 25.956522 | 89 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/VariableNamesInvalidTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.junit.Test;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
@SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE")
public class VariableNamesInvalidTest extends SolverBasedTest0.ParameterizedSolverBasedTest0 {
// currently the only invalid String is the empty String
@Test(expected = IllegalArgumentException.class)
public void testInvalidBoolVariable() {
@SuppressWarnings("unused")
Formula var = bmgr.makeVariable("");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidIntVariable() {
requireIntegers();
@SuppressWarnings("unused")
Formula var = imgr.makeVariable("");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidRatVariable() {
requireRationals();
@SuppressWarnings("unused")
Formula var = rmgr.makeVariable("");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidBVVariable() {
requireBitvectors();
@SuppressWarnings("unused")
Formula var = bvmgr.makeVariable(4, "");
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidFloatVariable() {
requireFloats();
@SuppressWarnings("unused")
Formula var = fpmgr.makeVariable("", FormulaType.getSinglePrecisionFloatingPointType());
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidIntArrayVariable() {
requireIntegers();
requireArrays();
@SuppressWarnings("unused")
Formula var = amgr.makeArray("", FormulaType.IntegerType, FormulaType.IntegerType);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidBvArrayVariable() {
requireBitvectors();
requireArrays();
@SuppressWarnings("unused")
Formula var =
amgr.makeArray(
"", FormulaType.getBitvectorTypeWithSize(2), FormulaType.getBitvectorTypeWithSize(2));
}
}
| 2,244 | 29.753425 | 98 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/VariableNamesTest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.visitors.DefaultBooleanFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager;
@RunWith(Parameterized.class)
@SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE")
public class VariableNamesTest extends SolverBasedTest0 {
private static final ImmutableList<String> NAMES =
ImmutableList.of(
"java-smt",
"JavaSMT",
"sosylab",
"test",
"foo",
"bar",
"baz",
"declare",
"exit",
"(exit)",
"!=",
"~",
",",
".",
":",
" ",
" ",
"(",
")",
"[",
"]",
"{",
"}",
"[]",
"\"",
"\"\"",
"\"\"\"",
// TODO next line is disabled because of a problem in MathSAT5 (version 5.6.3).
// "'", "''", "'''",
"\n",
"\t",
"\u0000",
"\u0001",
"\u1234",
"\u2e80",
" this is a quoted symbol ",
" so is \n this one ",
" \" can occur too ",
" af klj ^*0 asfe2 (&*)&(#^ $ > > >?\" ’]]984");
private static final ImmutableSet<String> FURTHER_SMTLIB2_KEYWORDS =
ImmutableSet.of(
"let",
"forall",
"exists",
"match",
"Bool",
"continued-execution",
"error",
"immediate-exit",
"incomplete",
"logic",
"memout",
"sat",
"success",
"theory",
"unknown",
"unsupported",
"unsat",
"_",
"as",
"BINARY",
"DECIMAL",
"HEXADECIMAL",
"NUMERAL",
"par",
"STRING",
"assert",
"check-sat",
"check-sat-assuming",
"declare-const",
"declare-datatype",
"declare-datatypes",
"declare-fun",
"declare-sort",
"define-fun",
"define-fun-rec",
"define-sort",
"echo",
"exit",
"get-assertions",
"get-assignment",
"get-info",
"get-model",
"get-option",
"get-proof",
"get-unsat-assumptions",
"get-unsat-core",
"get-value",
"pop",
"push",
"reset",
"reset-assertions",
"set-info",
"set-logic",
"set-option");
/**
* Some special chars are not allowed to appear in symbol names. See {@link
* AbstractFormulaManager#DISALLOWED_CHARACTERS}.
*/
@SuppressWarnings("javadoc")
private static final ImmutableSet<String> UNSUPPORTED_NAMES =
ImmutableSet.of(
"|",
"||",
"|||",
"|test",
"|test|",
"t|e|s|t",
"\\",
"\\s",
"\\|\\|",
"| this is a quoted symbol |",
"| so is \n this one |",
"| \" can occur too |",
"| af klj ^*0 asfe2 (&*)&(#^ $ > > >?\" ’]]984|");
protected List<String> getAllNames() {
return ImmutableList.<String>builder()
.addAll(NAMES)
.addAll(AbstractFormulaManager.BASIC_OPERATORS)
.addAll(AbstractFormulaManager.SMTLIB2_KEYWORDS)
.addAll(AbstractFormulaManager.DISALLOWED_CHARACTER_REPLACEMENT.values())
.addAll(FURTHER_SMTLIB2_KEYWORDS)
.addAll(UNSUPPORTED_NAMES)
.build();
}
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
boolean allowInvalidNames() {
return true;
}
@CanIgnoreReturnValue
private <T extends Formula> T createVariableWith(Function<String, T> creator, String name) {
if (allowInvalidNames() && !mgr.isValidName(name)) {
assertThrows(IllegalArgumentException.class, () -> creator.apply(name));
return null;
} else {
return creator.apply(name);
}
}
private <T extends Formula> void testName0(
String name, Function<String, T> creator, BiFunction<T, T, BooleanFormula> eq, boolean isUF)
throws SolverException, InterruptedException {
requireVisitor();
// create a variable
T var = createVariableWith(creator, name);
if (var == null) {
return;
}
// check whether it exists with the given name
Map<String, Formula> map = mgr.extractVariables(var);
if (isUF) {
assertThat(map).isEmpty();
map = mgr.extractVariablesAndUFs(var);
}
assertThat(map).hasSize(1);
assertThat(map).containsEntry(name, var);
// check whether we can create the same variable again
T var2 = createVariableWith(creator, name);
if (var2 == null) {
return;
}
// for simple formulas, we can expect a direct equality
// (for complex formulas this is not satisfied)
assertThat(var2).isEqualTo(var);
assertThat(var2.toString()).isEqualTo(var.toString());
assertThatFormula(eq.apply(var, var2)).isSatisfiable();
if (var instanceof FloatingPointFormula) {
// special case: NaN != NaN
assertThatFormula(bmgr.not(eq.apply(var, var2))).isSatisfiable();
} else {
assertThatFormula(bmgr.not(eq.apply(var, var2))).isUnsatisfiable();
assertThatFormula(eq.apply(var, var2)).isSatisfiableAndHasModel(1);
}
// check whether SMTLIB2-dump is possible
@SuppressWarnings("unused")
String dump = mgr.dumpFormula(eq.apply(var, var)).toString();
if (allowInvalidNames()) {
// try to create a new (!) variable with a different name, the escaped previous name.
assertThat(createVariableWith(creator, "|" + name + "|")).isEqualTo(null);
}
}
@Test
public void testBoolVariable() {
for (String name : getAllNames()) {
createVariableWith(bmgr::makeVariable, name);
}
}
@Test
public void testNameBool() throws SolverException, InterruptedException {
for (String name : getAllNames()) {
testName0(name, bmgr::makeVariable, bmgr::equivalence, false);
}
}
@Test
public void testNameInt() throws SolverException, InterruptedException {
requireIntegers();
for (String name : getAllNames()) {
testName0(name, imgr::makeVariable, imgr::equal, false);
}
}
@Test
public void testNameRat() throws SolverException, InterruptedException {
requireRationals();
for (String name : getAllNames()) {
testName0(name, rmgr::makeVariable, rmgr::equal, false);
}
}
@Test
public void testNameBV() throws SolverException, InterruptedException {
requireBitvectors();
for (String name : getAllNames()) {
testName0(name, s -> bvmgr.makeVariable(4, s), bvmgr::equal, false);
}
}
@Test
public void testNameFloat() throws SolverException, InterruptedException {
requireFloats();
for (String name : getAllNames()) {
testName0(
name,
s -> fpmgr.makeVariable(s, FormulaType.getSinglePrecisionFloatingPointType()),
fpmgr::equalWithFPSemantics,
false);
}
}
@Test
public void testNameIntArray() throws SolverException, InterruptedException {
requireIntegers();
requireArrays();
for (String name : getAllNames()) {
testName0(name, s -> amgr.makeArray(s, IntegerType, IntegerType), amgr::equivalence, false);
}
}
@Test
public void testNameBvArray() throws SolverException, InterruptedException {
requireBitvectors();
requireArrays();
// Someone who knows princess has to debug this!
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
for (String name : NAMES) {
testName0(
name,
s ->
amgr.makeArray(
s,
FormulaType.getBitvectorTypeWithSize(2),
FormulaType.getBitvectorTypeWithSize(2)),
amgr::equivalence,
false);
}
}
@Test
public void testNameUF1Bool() throws SolverException, InterruptedException {
requireIntegers();
for (String name : NAMES) {
testName0(
name,
s -> fmgr.declareAndCallUF(s, BooleanType, imgr.makeNumber(0)),
bmgr::equivalence,
true);
}
}
@Test
public void testNameUF1Int() throws SolverException, InterruptedException {
requireIntegers();
for (String name : NAMES) {
testName0(
name, s -> fmgr.declareAndCallUF(s, IntegerType, imgr.makeNumber(0)), imgr::equal, true);
}
}
@Test
public void testNameUFBv() throws SolverException, InterruptedException {
requireBitvectors();
// Someone who knows princess has to debug this!
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
for (String name : getAllNames()) {
testName0(
name,
s -> fmgr.declareAndCallUF(s, BooleanType, bvmgr.makeBitvector(2, 0)),
bmgr::equivalence,
true);
}
}
@Test
public void testNameUF2Bool() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula zero = imgr.makeNumber(0);
for (String name : NAMES) {
testName0(
name, s -> fmgr.declareAndCallUF(s, BooleanType, zero, zero), bmgr::equivalence, true);
}
}
@Test
public void testNameUF2Int() throws SolverException, InterruptedException {
requireIntegers();
IntegerFormula zero = imgr.makeNumber(0);
for (String name : NAMES) {
testName0(name, s -> fmgr.declareAndCallUF(s, IntegerType, zero, zero), imgr::equal, true);
}
}
@Test
public void testNameInQuantification() {
requireQuantifiers();
requireIntegers();
for (String name : getAllNames()) {
IntegerFormula var = createVariableWith(imgr::makeVariable, name);
if (var == null) {
continue;
}
IntegerFormula zero = imgr.makeNumber(0);
BooleanFormula eq = imgr.equal(var, zero);
BooleanFormula exists = qmgr.exists(var, eq);
BooleanFormula query = bmgr.and(bmgr.not(eq), exists);
// (var != 0) & (EX var: (var == 0))
assertThat(mgr.extractVariablesAndUFs(eq)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(eq)).containsEntry(name, var);
assertThat(mgr.extractVariablesAndUFs(query)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(query)).containsEntry(name, var);
assertThat(mgr.extractVariablesAndUFs(exists)).isEmpty();
mgr.visit(
query,
new DefaultFormulaVisitor<Void>() {
@Override
public Void visitQuantifier(
BooleanFormula pF,
Quantifier pQuantifier,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
if (solverToUse() != Solvers.PRINCESS) {
// TODO Princess does not (yet) return quantified variables.
assertThat(pBoundVariables).hasSize(1);
}
for (Formula f : pBoundVariables) {
Map<String, Formula> map = mgr.extractVariables(f);
assertThat(map).hasSize(1);
assertThat(map).containsEntry(name, f);
}
return null;
}
@Override
protected Void visitDefault(Formula pF) {
return null;
}
});
}
}
@Test
public void testNameInNestedQuantification() {
requireQuantifiers();
requireIntegers();
for (String name : getAllNames()) {
IntegerFormula var1 = createVariableWith(imgr::makeVariable, name + 1);
if (var1 == null) {
continue;
}
IntegerFormula var2 = createVariableWith(imgr::makeVariable, name + 2);
IntegerFormula var3 = createVariableWith(imgr::makeVariable, name + 3);
IntegerFormula var4 = createVariableWith(imgr::makeVariable, name + 4);
IntegerFormula zero = imgr.makeNumber(0);
// (v1 == 0) & (EX v2: ((v2 == v1) & (EX v3: ((v3 == v2) & (EX v4: (v4 == v3))))
BooleanFormula eq01 = imgr.equal(zero, var1);
BooleanFormula eq12 = imgr.equal(var1, var2);
BooleanFormula eq23 = imgr.equal(var2, var3);
BooleanFormula eq34 = imgr.equal(var3, var4);
BooleanFormula exists4 = qmgr.exists(var4, eq34);
BooleanFormula exists3 = qmgr.exists(var3, bmgr.and(eq23, exists4));
BooleanFormula exists2 = qmgr.exists(var2, bmgr.and(eq12, exists3));
BooleanFormula query = bmgr.and(eq01, exists2);
assertThat(mgr.extractVariablesAndUFs(eq01)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(eq01)).containsEntry(name + 1, var1);
assertThat(mgr.extractVariablesAndUFs(eq12)).hasSize(2);
assertThat(mgr.extractVariablesAndUFs(eq12)).containsEntry(name + 1, var1);
assertThat(mgr.extractVariablesAndUFs(eq12)).containsEntry(name + 2, var2);
assertThat(mgr.extractVariablesAndUFs(eq23)).hasSize(2);
assertThat(mgr.extractVariablesAndUFs(eq23)).containsEntry(name + 2, var2);
assertThat(mgr.extractVariablesAndUFs(eq23)).containsEntry(name + 3, var3);
assertThat(mgr.extractVariablesAndUFs(eq34)).hasSize(2);
assertThat(mgr.extractVariablesAndUFs(eq34)).containsEntry(name + 3, var3);
assertThat(mgr.extractVariablesAndUFs(eq34)).containsEntry(name + 4, var4);
assertThat(mgr.extractVariablesAndUFs(query)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(query)).containsEntry(name + 1, var1);
assertThat(mgr.extractVariablesAndUFs(exists2)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(exists2)).containsEntry(name + 1, var1);
assertThat(mgr.extractVariablesAndUFs(exists3)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(exists3)).containsEntry(name + 2, var2);
assertThat(mgr.extractVariablesAndUFs(exists4)).hasSize(1);
assertThat(mgr.extractVariablesAndUFs(exists4)).containsEntry(name + 3, var3);
mgr.visit(
query,
new DefaultFormulaVisitor<Void>() {
int depth = 1;
@Override
public Void visitQuantifier(
BooleanFormula pF,
Quantifier pQuantifier,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
if (solverToUse() != Solvers.PRINCESS) {
// TODO Princess does not return quantified variables.
assertThat(pBoundVariables).hasSize(1);
}
for (Formula f : pBoundVariables) {
Map<String, Formula> map = mgr.extractVariables(f);
assertThat(map).hasSize(1);
assertThat(map).containsEntry(name + depth, f);
}
depth++;
return null;
}
@Override
protected Void visitDefault(Formula pF) {
return null;
}
});
}
}
@Test
public void testBoolVariableNameInVisitor() {
requireVisitor();
for (String name : getAllNames()) {
BooleanFormula var = createVariableWith(bmgr::makeVariable, name);
if (var == null) {
continue;
}
bmgr.visit(
var,
new DefaultBooleanFormulaVisitor<Void>() {
@Override
protected Void visitDefault() {
throw new AssertionError("unexpected case");
}
@Override
public Void visitAtom(BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> pDecl) {
assertThat(pDecl.getName()).isEqualTo(name);
return null;
}
});
}
}
@Test
public void testBoolVariableDump() {
for (String name : getAllNames()) {
BooleanFormula var = createVariableWith(bmgr::makeVariable, name);
if (var != null) {
@SuppressWarnings("unused")
String dump = mgr.dumpFormula(var).toString();
}
}
}
@Test
public void testEqBoolVariableDump() {
for (String name : getAllNames()) {
BooleanFormula var = createVariableWith(bmgr::makeVariable, name);
if (var != null) {
@SuppressWarnings("unused")
String dump = mgr.dumpFormula(bmgr.equivalence(var, var)).toString();
}
}
}
@Test
public void testIntVariable() {
requireIntegers();
for (String name : getAllNames()) {
createVariableWith(imgr::makeVariable, name);
}
}
@Test
public void testInvalidRatVariable() {
requireRationals();
for (String name : getAllNames()) {
createVariableWith(rmgr::makeVariable, name);
}
}
@Test
public void testBVVariable() {
requireBitvectors();
for (String name : getAllNames()) {
createVariableWith(v -> bvmgr.makeVariable(4, v), name);
}
}
@Test
public void testInvalidFloatVariable() {
requireFloats();
for (String name : getAllNames()) {
createVariableWith(
v -> fpmgr.makeVariable(v, FormulaType.getSinglePrecisionFloatingPointType()), name);
}
}
@Test
public void testIntArrayVariable() {
requireArrays();
requireIntegers();
for (String name : getAllNames()) {
createVariableWith(v -> amgr.makeArray(v, IntegerType, IntegerType), name);
}
}
@Test
public void testBvArrayVariable() {
requireArrays();
requireBitvectors();
// Someone who knows princess has to debug this!
assume().that(solverToUse()).isNotEqualTo(Solvers.PRINCESS);
for (String name : getAllNames()) {
createVariableWith(
v ->
amgr.makeArray(
v,
FormulaType.getBitvectorTypeWithSize(2),
FormulaType.getBitvectorTypeWithSize(2)),
name);
}
}
@Test
public void sameBehaviorTest() {
for (String name : getAllNames()) {
if (mgr.isValidName(name)) {
// should pass without exception
AbstractFormulaManager.checkVariableName(name);
} else {
assertThrows(
IllegalArgumentException.class, () -> AbstractFormulaManager.checkVariableName(name));
}
}
}
}
| 19,853 | 29.544615 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/test/package-info.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
/** Solver-independent tests and test utilities for the solver API. */
@com.google.errorprone.annotations.CheckReturnValue
@javax.annotation.ParametersAreNonnullByDefault
@org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault
package org.sosy_lab.java_smt.test;
| 512 | 35.642857 | 70 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/utils/PrettyPrinter.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.utils;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
public class PrettyPrinter {
public enum PrinterOption {
/** introduce newlines only for boolean operations, instead of for all operations. */
SPLIT_ONLY_BOOLEAN_OPERATIONS
}
private final FormulaManager fmgr;
public PrettyPrinter(FormulaManager pFmgr) {
fmgr = pFmgr;
}
/**
* This method returns a multi-line String with pretty-formatted and indented subformulas.
*
* <p>The String representation might contain solver-specific symbols that appear during a
* visitation of the formula. The returned String is intended to be human-readable and should not
* be used for further processing. The formatting of this string might change with future
* development and thus is not considered as "stable". If a user wants to apply further
* processing, we refer to {@link FormulaManager#dumpFormula} that provides machine-readable
* SMTLIB2.
*/
public String formulaToString(Formula f, PrinterOption... options) {
StringBuilder str = new StringBuilder();
fmgr.visit(f, new PrettyPrintVisitor(fmgr, str, ImmutableSet.copyOf(options)));
return str.toString();
}
/**
* This method returns a Graphviz/Dot representation of the given formula.
*
* <p>The graph representation might contain solver-specific symbols that appear during a
* visitation of the formula. The returned String is intended to be a human-readable graph for
* Graphviz/Dot and should not be used for further processing. The formatting of this string might
* change with future development and thus is not considered as "stable". If a user wants to apply
* further processing, we refer to {@link FormulaManager#dumpFormula} that provides
* machine-readable SMTLIB2.
*/
public String formulaToDot(Formula f, PrinterOption... options) {
DotVisitor plotter = new DotVisitor(ImmutableSet.copyOf(options));
fmgr.visitRecursively(f, plotter);
return plotter.toString();
}
private static boolean isBooleanFunction(FunctionDeclarationKind kind) {
switch (kind) {
case AND:
case OR:
case NOT:
case ITE:
case IFF:
case XOR:
case IMPLIES:
return true;
default:
return false;
}
}
private static String getColor(FunctionDeclarationKind kind) {
switch (kind) {
case AND:
return "lightblue";
case OR:
return "lightgreen";
case NOT:
return "orange";
case ITE:
return "yellow";
case IFF:
case XOR:
case IMPLIES:
return "lightpink";
default:
return "white";
}
}
private static String getEdgeLabel(FunctionDeclarationKind kind, int operandId) {
// for some functions, the order of operands is not important, so we return an empty String
switch (kind) {
case AND:
case OR:
case NOT:
case IFF:
case XOR:
return "";
default:
return Integer.toString(operandId);
}
}
private static class PrettyPrintVisitor extends DefaultFormulaVisitor<Void> {
private final FormulaManager fmgr;
private final StringBuilder out;
private final boolean onlyBooleanOperations;
private int depth = 0;
/** flag to enable or disable splitting formulas in multiple lines. */
private boolean enableSplitting = true;
private PrettyPrintVisitor(
FormulaManager pFmgr, StringBuilder pStr, Collection<PrinterOption> pOptions) {
fmgr = pFmgr;
out = pStr;
onlyBooleanOperations = pOptions.contains(PrinterOption.SPLIT_ONLY_BOOLEAN_OPERATIONS);
}
/** add a newline and space for indent if required, and a simple whitespace otherwise. */
private void newline() {
if (enableSplitting) {
if (out.length() != 0) {
out.append(System.lineSeparator());
}
out.append(" ".repeat(depth)); // two spaces indent is sufficient
} else {
out.append(" "); // just a separator between two tokens
}
}
@Override
protected Void visitDefault(Formula pF) {
newline();
out.append(pF);
return null;
}
@Override
public Void visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
newline();
out.append("(").append(pFunctionDeclaration.getName());
boolean splitNested = true;
// we only change the flag
// - if splitting is still allowed (recursive formulas!) and
// - if we should not split INT or BV arithmetics
if (enableSplitting
&& onlyBooleanOperations
&& !isBooleanFunction(pFunctionDeclaration.getKind())) {
splitNested = false;
}
if (!splitNested) { // disable deeper splitting
enableSplitting = false;
}
depth++;
for (Formula arg : pArgs) {
fmgr.visit(arg, this);
}
depth--;
if (enableSplitting) { // avoid superflous whitespace before closing bracket
newline();
}
out.append(")");
if (!splitNested) { // reset flag
enableSplitting = true;
}
return null;
}
}
private static class DotVisitor extends DefaultFormulaVisitor<TraversalProcess> {
private final Map<Formula, Integer> nodeMapping = new LinkedHashMap<>();
private final UniqueIdGenerator id = new UniqueIdGenerator();
private final boolean onlyBooleanOperations;
// start of dot-file, rest will be appended on visitation
private final StringBuilder out =
new StringBuilder(
"digraph SMT {" + System.lineSeparator() + " rankdir=LR" + System.lineSeparator());
// let's print leave-nodes lazily, having them on same rank looks nicer in the plot.
private final List<String> leaves = new ArrayList<>();
private DotVisitor(Collection<PrinterOption> pOptions) {
onlyBooleanOperations = pOptions.contains(PrinterOption.SPLIT_ONLY_BOOLEAN_OPERATIONS);
}
@Override
public String toString() {
// let's put non-expanded leaf-nodes onto the right side
if (!leaves.isEmpty()) {
out.append(" { rank=same;").append(System.lineSeparator());
leaves.forEach(out::append);
out.append(" }").append(System.lineSeparator());
}
// end of dot-file
out.append("}");
return out.toString();
}
private int getId(Formula f) {
return nodeMapping.computeIfAbsent(f, unused -> id.getFreshId());
}
private String formatNode(Formula f, String label) {
return formatNode(f, label, "rectangle", "white");
}
private String formatNode(Formula f, String label, String shape, String color) {
return String.format(
" %d [label=\"%s\", shape=\"%s\", style=\"filled\", fillcolor=\"%s\"];%n",
getId(f), label, shape, color);
}
private String formatEdge(Formula from, Formula to, String label) {
return String.format(" %d -> %d [label=\"%s\"];%n", getId(from), getId(to), label);
}
@Override
protected TraversalProcess visitDefault(Formula pF) {
out.append(formatNode(pF, pF.toString()));
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitConstant(Formula pF, Object value) {
out.append(formatNode(pF, pF.toString(), "rectangle", "grey"));
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
FunctionDeclarationKind kind = pFunctionDeclaration.getKind();
// we skip subformulas
// - if splitting is still allowed (recursive formulas!) and
// - if we should not split INT or BV arithmetics
if (onlyBooleanOperations && !isBooleanFunction(kind)) {
// for leaves, we just dump the formula. This might include redundant subformulas.
leaves.add(" " + formatNode(pF, pF.toString()));
return TraversalProcess.SKIP;
} else {
String color = getColor(kind);
// we expect small labels, so circle-shape is sufficiently small
out.append(formatNode(pF, pFunctionDeclaration.getName(), "circle", color));
int operandId = 0;
for (Formula arg : pArgs) {
out.append(formatEdge(pF, arg, getEdgeLabel(kind, operandId++)));
}
return TraversalProcess.CONTINUE;
}
}
}
}
| 9,237 | 32.230216 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/utils/SolverUtils.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.utils;
import org.sosy_lab.java_smt.api.FormulaManager;
/** Central entry point for all utility classes. */
public final class SolverUtils {
private SolverUtils() {}
/**
* Creates a new {@link UfElimination} instance.
*
* @param pFormulaManager the {@link FormulaManager} to be used
* @return a new {@link UfElimination} instance
*/
public static UfElimination ufElimination(FormulaManager pFormulaManager) {
return new UfElimination(pFormulaManager);
}
/**
* Creates a new {@link PrettyPrinter} instance.
*
* @param pFormulaManager the {@link FormulaManager} to be used
* @return a new {@link PrettyPrinter} instance
*/
public static PrettyPrinter prettyPrinter(FormulaManager pFormulaManager) {
return new PrettyPrinter(pFormulaManager);
}
}
| 1,071 | 27.210526 | 77 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/utils/UfElimination.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.utils;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.difference;
import com.google.auto.value.AutoValue;
import com.google.common.base.Verify;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import com.google.errorprone.annotations.CheckReturnValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
/**
* UfElimination replaces UFs by fresh variables and adds constraints to enforce the functional
* consistency.
*/
public class UfElimination {
public static class Result {
private final BooleanFormula formula;
private final BooleanFormula constraints;
private final ImmutableMap<Formula, Formula> substitutions;
private final ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs;
public static Result empty(FormulaManager pFormulaManager) {
BooleanFormula trueFormula = pFormulaManager.getBooleanFormulaManager().makeTrue();
return new Result(trueFormula, trueFormula, ImmutableMap.of(), ImmutableListMultimap.of());
}
Result(
BooleanFormula pFormula,
BooleanFormula pConstraints,
ImmutableMap<Formula, Formula> pSubstitutions,
ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs) {
formula = checkNotNull(pFormula);
constraints = checkNotNull(pConstraints);
substitutions = checkNotNull(pSubstitutions);
ufs = checkNotNull(pUfs);
}
/**
* @return the new {@link Formula} without UFs
*/
public BooleanFormula getFormula() {
return formula;
}
/**
* @return the constraints enforcing the functional consistency.
*/
public BooleanFormula getConstraints() {
return constraints;
}
/**
* @return the substitution used to replace UFs
*/
public Map<Formula, Formula> getSubstitution() {
return substitutions;
}
/**
* @return all eliminated application of Ufs
*/
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> getUfs() {
return ufs;
}
}
private static final UniqueIdGenerator UNIQUE_ID_GENERATOR = new UniqueIdGenerator();
private static final String prefix = "__UF_fresh_";
private final BooleanFormulaManager bfmgr;
private final FormulaManager fmgr;
UfElimination(FormulaManager pFmgr) {
bfmgr = pFmgr.getBooleanFormulaManager();
fmgr = pFmgr;
}
/**
* Applies the Ackermann transformation to the given {@link Formula}. Quantified formulas are not
* supported.
*
* @param f the {@link Formula} to remove all Ufs from
* @return the new {@link Formula} and the substitution done during transformation
*/
public BooleanFormula eliminateUfs(BooleanFormula f) {
Result result = eliminateUfs(f, Result.empty(fmgr));
return fmgr.getBooleanFormulaManager().and(result.getFormula(), result.getConstraints());
}
/**
* Applies the Ackermann transformation to the given {@link Formula} with respect to the {@link
* Result} of another formula. Quantified formulas are not supported.
*
* @param pF the {@link Formula} to remove all Ufs from
* @param pOtherResult result of eliminating Ufs in another {@link BooleanFormula}
* @return the {@link Result} of the Ackermannization
*/
public Result eliminateUfs(BooleanFormula pF, Result pOtherResult) {
checkArgument(!isQuantified(pF));
BooleanFormula f;
if (!pOtherResult.getSubstitution().isEmpty()) {
f = fmgr.substitute(pF, pOtherResult.getSubstitution());
} else {
f = pF;
}
int depth = getNestingDepthOfUfs(f);
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = findUFs(f);
merge(ufs, pOtherResult);
ImmutableMap.Builder<Formula, Formula> substitutionsBuilder = ImmutableMap.builder();
List<BooleanFormula> extraConstraints = new ArrayList<>();
for (FunctionDeclaration<?> function : ufs.keySet()) {
List<UninterpretedFunctionApplication> applications = new ArrayList<>(ufs.get(function));
for (int idx1 = 0; idx1 < applications.size(); idx1++) {
UninterpretedFunctionApplication application = applications.get(idx1);
Formula uf = application.getFormula();
List<Formula> args = application.getArguments();
Formula substitution = application.getSubstitution();
substitutionsBuilder.put(uf, substitution);
for (int idx2 = idx1 + 1; idx2 < applications.size(); idx2++) {
UninterpretedFunctionApplication application2 = applications.get(idx2);
List<Formula> otherArgs = application2.getArguments();
/*
* Add constraints to enforce functional consistency.
*/
Verify.verify(args.size() == otherArgs.size());
BooleanFormula argumentsEquality =
Streams.zip(args.stream(), otherArgs.stream(), this::makeEqual)
.collect(bfmgr.toConjunction());
BooleanFormula functionEquality = makeEqual(substitution, application2.getSubstitution());
extraConstraints.add(bfmgr.implication(argumentsEquality, functionEquality));
}
}
}
// Get rid of UFs.
ImmutableMap<Formula, Formula> substitutions = substitutionsBuilder.buildOrThrow();
BooleanFormula formulaWithoutUFs = fmgr.substitute(f, substitutions);
// substitute all UFs in the additional constraints,
// required if UFs are arguments of UFs, e.g. uf(uf(1, 2), 2)
for (int i = 0; i < depth; i++) {
extraConstraints.replaceAll(c -> fmgr.substitute(c, substitutions));
}
Map<Formula, Formula> otherSubstitution =
difference(pOtherResult.getSubstitution(), substitutions).entriesOnlyOnLeft();
substitutionsBuilder.putAll(otherSubstitution);
ImmutableMap<Formula, Formula> allSubstitutions = substitutionsBuilder.buildOrThrow();
BooleanFormula constraints = bfmgr.and(extraConstraints);
return new Result(
formulaWithoutUFs, constraints, allSubstitutions, ImmutableListMultimap.copyOf(ufs));
}
private void merge(
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs,
Result pPreviousResult) {
for (Map.Entry<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufInOtherFormula :
pPreviousResult.getUfs().entries()) {
if (pUfs.containsKey(ufInOtherFormula.getKey())) {
pUfs.put(ufInOtherFormula.getKey(), ufInOtherFormula.getValue());
}
}
}
@SuppressWarnings("unchecked")
@CheckReturnValue
private BooleanFormula makeEqual(Formula pLhs, Formula pRhs) {
BooleanFormula t;
if (pLhs instanceof BooleanFormula && pRhs instanceof BooleanFormula) {
t = bfmgr.equivalence((BooleanFormula) pLhs, (BooleanFormula) pRhs);
} else if (pLhs instanceof IntegerFormula && pRhs instanceof IntegerFormula) {
t = fmgr.getIntegerFormulaManager().equal((IntegerFormula) pLhs, (IntegerFormula) pRhs);
} else if (pLhs instanceof StringFormula && pRhs instanceof StringFormula) {
t = fmgr.getStringFormulaManager().equal((StringFormula) pLhs, (StringFormula) pRhs);
} else if (pLhs instanceof NumeralFormula && pRhs instanceof NumeralFormula) {
t = fmgr.getRationalFormulaManager().equal((NumeralFormula) pLhs, (NumeralFormula) pRhs);
} else if (pLhs instanceof BitvectorFormula) {
t = fmgr.getBitvectorFormulaManager().equal((BitvectorFormula) pLhs, (BitvectorFormula) pRhs);
} else if (pLhs instanceof FloatingPointFormula && pRhs instanceof FloatingPointFormula) {
FloatingPointFormulaManager fpfmgr = fmgr.getFloatingPointFormulaManager();
t = fpfmgr.equalWithFPSemantics((FloatingPointFormula) pLhs, (FloatingPointFormula) pRhs);
} else if (pLhs instanceof ArrayFormula<?, ?> && pRhs instanceof ArrayFormula<?, ?>) {
ArrayFormula<?, ?> lhs = (ArrayFormula<?, ?>) pLhs;
@SuppressWarnings("rawtypes")
ArrayFormula rhs = (ArrayFormula) pRhs;
t = fmgr.getArrayFormulaManager().equivalence(lhs, rhs);
} else {
throw new IllegalArgumentException("Not supported interface");
}
return t;
}
private boolean isQuantified(Formula f) {
AtomicBoolean result = new AtomicBoolean();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula pF) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitQuantifier(
BooleanFormula pF,
Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
result.set(true);
return TraversalProcess.ABORT;
}
});
return result.get();
}
private int getNestingDepthOfUfs(Formula pFormula) {
return fmgr.visit(
pFormula,
new DefaultFormulaVisitor<>() {
@Override
protected Integer visitDefault(Formula pF) {
return 0;
}
@Override
public Integer visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
int depthOfArgs = pArgs.stream().mapToInt(f -> fmgr.visit(f, this)).max().orElse(0);
// count only UFs
if (pFunctionDeclaration.getKind() == FunctionDeclarationKind.UF) {
return depthOfArgs + 1;
} else {
return depthOfArgs;
}
}
@Override
public Integer visitQuantifier(
BooleanFormula pF,
QuantifiedFormulaManager.Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
return fmgr.visit(pBody, this);
}
});
}
private Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> findUFs(
Formula pFormula) {
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = HashMultimap.create();
fmgr.visitRecursively(
pFormula,
new DefaultFormulaVisitor<>() {
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> decl) {
if (decl.getKind() == FunctionDeclarationKind.UF) {
Formula substitution = freshUfReplaceVariable(decl.getType());
ufs.put(decl, UninterpretedFunctionApplication.create(f, args, substitution));
}
return TraversalProcess.CONTINUE;
}
});
return ufs;
}
private Formula freshUfReplaceVariable(FormulaType<?> pType) {
return fmgr.makeVariable(pType, prefix + UNIQUE_ID_GENERATOR.getFreshId());
}
@AutoValue
abstract static class UninterpretedFunctionApplication {
static UninterpretedFunctionApplication create(
Formula pF, List<Formula> pArguments, Formula pSubstitution) {
return new AutoValue_UfElimination_UninterpretedFunctionApplication(
pF, ImmutableList.copyOf(pArguments), pSubstitution);
}
abstract Formula getFormula();
abstract ImmutableList<Formula> getArguments();
abstract Formula getSubstitution();
}
}
| 13,117 | 36.587393 | 100 | java |
java-smt | java-smt-master/src/org/sosy_lab/java_smt/utils/package-info.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
/** Utility classes implementing algorithms based on the API of JavaSMT. */
@com.google.errorprone.annotations.CheckReturnValue
@javax.annotation.ParametersAreNonnullByDefault
@org.sosy_lab.common.annotations.FieldsAreNonnullByDefault
@org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault
package org.sosy_lab.java_smt.utils;
| 577 | 37.533333 | 75 | java |
JSAT | JSAT-master/JSAT/src/jsat/ColumnMajorStore.java | /*
* Copyright (C) 2018 Edward Raff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jsat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.DataPoint;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.SparseVector;
import jsat.linear.SubVector;
import jsat.linear.Vec;
import jsat.math.OnLineStatistics;
import jsat.utils.DoubleList;
import jsat.utils.IntList;
/**
*
* @author Edward Raff
*/
public class ColumnMajorStore implements DataStore
{
private boolean sparse;
int size = 0;
List<Vec> columns;
List<IntList> cat_columns;
CategoricalData[] cat_info;
/**
* Creates a new Data Store to add points to, where the number of features
* is not known in advance.
*/
public ColumnMajorStore(boolean sparse)
{
this(0, null, sparse);
}
/**
* Creates a new Data Store to add points to, where the number of features
* is not known in advance.
*/
public ColumnMajorStore()
{
this(0, null);
}
@Override
public CategoricalData[] getCategoricalDataInfo()
{
return cat_info;
}
/**
* Creates a new Data Store with the intent for a specific number of features known ahead of time.
* @param numNumeric the number of numeric features to be in the data store
* @param cat_info the information about the categorical data
*/
public ColumnMajorStore(int numNumeric, CategoricalData[] cat_info)
{
this(numNumeric, cat_info, true);
}
/**
* Creates a new Data Store with the intent for a specific number of features known ahead of time.
* @param numNumeric the number of numeric features to be in the data store
* @param cat_info the information about the categorical data
* @param sparse if the columns should be stored in a sparse format
*/
public ColumnMajorStore(int numNumeric, CategoricalData[] cat_info, boolean sparse)
{
this.columns = new ArrayList<>(numNumeric);
for(int i = 0; i < numNumeric; i++)
this.columns.add(sparse ? new SparseVector(10) : new DenseVector(10));
this.cat_info = cat_info;
this.cat_columns = new ArrayList<>();
for(int i = 0; i < (cat_info == null ? 0 : cat_info.length); i++)
this.cat_columns.add(new IntList());
this.sparse = sparse;
}
/**
* Copy constructor
* @param toCopy the object to copy
*/
public ColumnMajorStore(ColumnMajorStore toCopy)
{
this.columns = new ArrayList<>(toCopy.columns.size());
for(Vec v : toCopy.columns)
this.columns.add(v.clone());
this.cat_columns = new ArrayList<>(toCopy.cat_columns.size());
for(IntList cv : toCopy.cat_columns)
this.cat_columns.add(new IntList(cv));
if(toCopy.cat_info != null)
this.cat_info = CategoricalData.copyOf(toCopy.cat_info);
this.size = toCopy.size;
this.sparse = toCopy.sparse;
}
@Override
public boolean rowMajor()
{
return false;
}
@Override
public void setCategoricalDataInfo(CategoricalData[] cat_info)
{
this.cat_info = cat_info;
}
@Override
public int numCategorical()
{
return cat_columns.size();
}
@Override
public int numNumeric()
{
return columns.size();
}
@Override
public void setNumNumeric(int d)
{
if(d < 0)
throw new RuntimeException("Can not store a negative number of features (" +d + ")");
//do we need to add more?
while(columns.size() < d)
this.columns.add(sparse ? new SparseVector(10) : new DenseVector(10));
//or do we need to remove?
while(columns.size() > d)
columns.remove(columns.size()-1);
//now we should be the same length!
}
@Override
public void addDataPoint(DataPoint dp)
{
Vec x = dp.getNumericalValues();
int[] x_c = dp.getCategoricalValues();
int pos = size++;
//make sure we have capacity in the columns
while(columns.size() < x.length())
columns.add(sparse ? new SparseVector(size) : new DenseVector(size));
while(cat_columns.size() < x_c.length)
{
int[] newCol = new int[size];
Arrays.fill(newCol, -1);//All previous entries have a missing value indication (-1) now.
cat_columns.add(IntList.view(newCol));
}
//add numeric features
for(IndexValue iv : x)
{
int d = iv.getIndex();
double v = iv.getValue();
Vec x_d = columns.get(d);
if(x_d.length() <= pos)//We need to increase the size of x_d
x_d.setLength(size*2);
//size is now correct, we can set the values
x_d.set(pos, v);
}
//add categorical features
for(int d = 0; d < x_c.length; d++)
{
IntList col = cat_columns.get(d);
while(col.size() <= pos)//fill missing values with missing value indicator
col.add(-1);
//we filled up to the current value, so now we can call set and
// handle 3 cases with same code. Col is correct size and col is too
//small or too large.
col.set(pos, x_c[d]);
}
//add missing categorical features
for(int d = x_c.length; d < cat_columns.size(); d++)
{
IntList col = cat_columns.get(d);
while(col.size() <= pos)//fill missing values with missing value indicator
col.add(-1);
}
}
@Override
public Vec getNumericColumn(int i)
{
return columns.get(i);
}
@Override
public DataPoint getDataPoint(int i)
{
if(i >= size)
throw new IndexOutOfBoundsException("Requested datapoint " + i + " but index has only " + size + " datums");
int d_n = numNumeric();
int d_c = numCategorical();
//best guess on sparseness
Vec x = sparse ? new SparseVector(d_n) : new DenseVector(d_n);
int[] cat = new int[d_c];
for(int j = 0; j < d_n; j++)
{
Vec col_j = columns.get(j);
if(col_j.length() > i)
x.set(j, col_j.get(i));
//else, no more occurances of that featre by this point - so skip.
}
for(int j = 0; j < d_c; j++)
cat[j] = cat_columns.get(j).get(i);
if(sparse && x.nnz() > d_n/2)
x = new DenseVector(x);//denseify
return new DataPoint(x, cat, cat_info);
}
@Override
public void setDataPoint(int i, DataPoint dp)
{
if(i >= size)
throw new IndexOutOfBoundsException("Requested datapoint " + i + " but index has only " + size + " datums");
int d_n = numNumeric();
int d_c = numCategorical();
Vec x = dp.getNumericalValues();
int[] cat = dp.getCategoricalValues();
for(int j = 0; j < d_n; j++)
{
Vec tmp = columns.get(j);
tmp.set(i, 0);
}
for(IndexValue iv : x)
columns.get(iv.getIndex()).set(i, iv.getValue());
for(int j = 0; j < d_c; j++)
cat_columns.get(j).set(i, cat[j]);
}
@Override
public void finishAdding()
{
if(cat_info == null)
{
cat_info = new CategoricalData[numCategorical()];
for(int j = 0; j < cat_info.length; j++)
{
int options = cat_columns.get(j).streamInts().max().orElse(1);
cat_info[j] = new CategoricalData(Math.max(options, 1));//max incase all are missing
}
}
for(int i = 0; i < columns.size(); i++)
{
Vec v = columns.get(i);
v.setLength(size);
}
}
@Override
public Vec[] getNumericColumns(Set<Integer> skipColumns)
{
Vec[] toRet = new Vec[numNumeric()];
for(int j = 0; j < toRet.length; j++)
if(!skipColumns.contains(j))
{
toRet[j] = columns.get(j);
if(toRet[j].length() != size())
toRet[j] = new SubVector(0, size, toRet[j]);
}
return toRet;
}
@Override
public int size()
{
return size;
}
@Override
public OnLineStatistics getSparsityStats()
{
OnLineStatistics stats = new OnLineStatistics();
for(Vec v : columns)
{
if(v.isSparse())
stats.add(v.nnz() / (double)size);
else
stats.add(1.0);
}
return stats;
}
@Override
public ColumnMajorStore clone()
{
return new ColumnMajorStore(this);
}
@Override
public ColumnMajorStore emptyClone()
{
return new ColumnMajorStore(columns.size(), cat_info, sparse);
}
@Override
public int[] getCatColumn(int i)
{
if (i < 0 || i >= numCategorical())
throw new IndexOutOfBoundsException("There is no index for column " + i);
return Arrays.copyOf(cat_columns.get(i).streamInts().toArray(), size());
}
}
| 10,148 | 28.675439 | 120 | java |
JSAT | JSAT-master/JSAT/src/jsat/DataSet.java |
package jsat;
import java.lang.ref.SoftReference;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.DataPoint;
import jsat.datatransform.DataTransform;
import jsat.datatransform.FixedDataTransform;
import jsat.datatransform.InPlaceTransform;
import jsat.linear.*;
import jsat.math.OnLineStatistics;
import jsat.utils.IntList;
import jsat.utils.ListUtils;
import jsat.utils.concurrent.ParallelUtils;
import jsat.utils.random.RandomUtil;
/**
* This is the base class for representing a data set. A data set contains multiple samples,
* each of which should have the same number of attributes. Conceptually, each
* {@link DataPoint} represents a row in the data set, and the attributes form the columns.
*
* @author Edward Raff
* @param <Type>
*/
public abstract class DataSet<Type extends DataSet>
{
/**
* The number of numerical values each data point must have
*/
protected int numNumerVals;
/**
* Contains the categories for each of the categorical variables
*/
protected CategoricalData[] categories;
/**
* The map of the names of the numeric variables.
*/
protected Map<Integer, String> numericalVariableNames;
/**
* The backing store that holds all data points
*/
protected DataStore datapoints;
/**
* Store all the weights for each data point. If null, indicates an implicit
* value of 1.0 for each datumn.
*/
protected double[] weights;
/**
* Creates a new dataset containing the given datapoints. The number of
* features and categorical data information will be obtained from the
* DataStore.
*
* @param datapoints the collection of data points to create a dataset from
*/
public DataSet(DataStore datapoints)
{
this.datapoints = datapoints;
this.numNumerVals = datapoints.numNumeric();
this.categories = datapoints.getCategoricalDataInfo();
this.weights = null;
if(this.numNumerVals == 0 && (this.categories == null || this.categories.length == 0 ))
throw new IllegalArgumentException("Input must have a non-zero number of features defined");
this.numericalVariableNames = new HashMap<>();
}
/**
* Creates a new empty data set
*
* @param numerical the number of numerical features for points in this
* dataset
* @param categories the information and number of categorical features in
* this dataset
*/
public DataSet(int numerical, CategoricalData[] categories)
{
this.categories = categories;
this.numNumerVals = numerical;
this.datapoints = DataStore.DEFAULT_STORE.emptyClone();
this.datapoints.setNumNumeric(numerical);
this.datapoints.setCategoricalDataInfo(categories);
this.numericalVariableNames = new HashMap<>();
this.weights = null;
}
/**
* This method changes the back-end store used to hold and represent data
* points. Changing this may be beneficial for expert users who know how
* their data will be accessed, or need to make modifications for more
* efficient storage.<br>
* If the currently data store is not empty, it's contents will be copied to
* the new store. <br>
* If the provided data store is not empty, and error will occur.
*
* @param store the new method for stroing data points
*/
public void setDataStore(DataStore store)
{
if(store.size() > 0)
throw new RuntimeException("A non-empty data store was provided to an already existing dataset object.");
store.setCategoricalDataInfo(this.datapoints.getCategoricalDataInfo());
store.setNumNumeric(numNumerVals);
if(this.datapoints.size() > 0)
{
for(int i = 0; i < this.datapoints.size(); i++)
store.addDataPoint(this.getDataPoint(i));
}
this.datapoints = store;
}
/**
*
* @return {@code true} if row-major traversal should be the preferred
* iteration order for this data store, or {@code false} if column-major
* should be preferred.
*/
public boolean rowMajor()
{
return datapoints.rowMajor();
}
/**
* Sets the unique name associated with the <tt>i</tt>'th numeric attribute. All strings will be converted to lower case first.
*
* @param name the name to use
* @param i the <tt>i</tt>th attribute.
* @return <tt>true</tt> if the value was set, <tt>false</tt> if it was not set because an invalid index was given .
*/
public boolean setNumericName(String name, int i)
{
if(i < getNumNumericalVars() && i >= 0)
numericalVariableNames.put(i, name);
else
return false;
return true;
}
/**
* Returns the name used for the <tt>i</tt>'th numeric attribute.
* @param i the <tt>i</tt>th attribute.
* @return the name used for the <tt>i</tt>'th numeric attribute.
*/
public String getNumericName(int i )
{
if(i < getNumNumericalVars() && i >= 0)
return numericalVariableNames.getOrDefault(i, "Numeric Feature " + i);
else
throw new IndexOutOfBoundsException("Can not acces variable for invalid index " + i );
}
/**
* Returns the name used for the <tt>i</tt>'th categorical attribute.
* @param i the <tt>i</tt>th attribute.
* @return the name used for the <tt>i</tt>'th categorical attribute.
*/
public String getCategoryName(int i )
{
if(i < getNumCategoricalVars() && i >= 0)
return categories[i].getCategoryName();
else
throw new IndexOutOfBoundsException("Can not acces variable for invalid index " + i );
}
/**
* Applies the given transformation to all points in this data set,
* replacing each data point with the new value. No mutation of the data
* points will occur
*
* @param dt the transformation to apply
*/
public void applyTransform(DataTransform dt)
{
DataSet.this.applyTransform(dt, false);
}
/**
* Applies the given transformation to all points in this data set,
* replacing each data point with the new value. No mutation of the data
* points will occur
*
* @param dt the transformation to apply
*/
public void applyTransform(FixedDataTransform dt)
{
DataSet.this.applyTransform(dt, false);
}
/**
* Applies the given transformation to all points in this data set in
* parallel, replacing each data point with the new value. No mutation of
* the data points will occur.
*
* @param dt the transformation to apply
* @param parallel whether or not to perform the transform in parallel or not.
*/
public void applyTransform(DataTransform dt, boolean parallel)
{
applyTransformMutate(dt, false, parallel);
}
/**
* Applies the given transformation to all points in this data set in
* parallel, replacing each data point with the new value. No mutation of
* the data points will occur.
*
* @param dt the transformation to apply
* @param parallel whether or not to perform the transform in parallel or not.
*/
public void applyTransform(FixedDataTransform dt, boolean parallel)
{
applyTransformMutate(new DataTransform()
{
@Override
public DataPoint transform(DataPoint dp)
{
return dt.transform(dp);
}
@Override
public void fit(DataSet data)
{
//NOP
}
@Override
public DataTransform clone()
{
return this;
}
}, false, parallel);
}
/**
* Applies the given transformation to all points in this data set. If the
* transform supports mutating the original data points, this will be
* applied if {@code mutableTransform} is set to {@code true}
*
* @param dt the transformation to apply
* @param mutate {@code true} to mutableTransform the original data points,
* {@code false} to ignore the ability to mutableTransform and replace the original
* data points.
*/
public void applyTransformMutate(DataTransform dt, boolean mutate)
{
applyTransformMutate(dt, mutate, false);
}
/**
* Applies the given transformation to all points in this data set in
* parallel. If the transform supports mutating the original data points,
* this will be applied if {@code mutableTransform} is set to {@code true}
*
* @param dt the transformation to apply
* @param mutate {@code true} to mutableTransform the original data points,
* {@code false} to ignore the ability to mutableTransform and replace the original
* @param parallel whether or not to perform the transform in parallel or not.
*/
public void applyTransformMutate(final DataTransform dt, boolean mutate, boolean parallel)
{
if (mutate && dt instanceof InPlaceTransform)
{
final InPlaceTransform ipt = (InPlaceTransform) dt;
ParallelUtils.range(size(), parallel)
.forEach(i->ipt.mutableTransform(getDataPoint(i)));
}
else
{
ParallelUtils.range(size(), parallel).forEach(i->setDataPoint(i, dt.transform(getDataPoint(i))));
this.datapoints.setNumNumeric(getDataPoint(0).numNumericalValues());
this.datapoints.setCategoricalDataInfo(getDataPoint(0).getCategoricalData());
}
//TODO this should be added to DataTransform
numNumerVals = getDataPoint(0).numNumericalValues();
categories = getDataPoint(0).getCategoricalData();
if (this.numericalVariableNames != null)
this.numericalVariableNames.clear();
}
/**
* This method will replace every numeric feature in this dataset with a Vec
* object from the given list. All vecs in the given list must be of the
* same size.
*
* @param newNumericFeatures the list of new numeric features to use
*/
public void replaceNumericFeatures(List<Vec> newNumericFeatures)
{
if(this.size() != newNumericFeatures.size())
throw new RuntimeException("Input list does not have the same not of dataums as the dataset");
for(int i = 0; i < newNumericFeatures.size(); i++)
{
DataPoint dp_i = getDataPoint(i);
setDataPoint(i, new DataPoint(newNumericFeatures.get(i), dp_i.getCategoricalValues(), dp_i.getCategoricalData()));
}
this.numNumerVals = getDataPoint(0).numNumericalValues();
if (this.numericalVariableNames != null)
this.numericalVariableNames.clear();
}
/**
* Adds a new datapoint to this set.This method is protected, as not all
* datasets will be satisfied by adding just a data point.
*
* @param dp the datapoint to add
* @param weight weight of the point to add
*/
protected void base_add(DataPoint dp, double weight)
{
datapoints.addDataPoint(dp);
setWeight(size()-1, weight);
}
/**
* Returns the <tt>i</tt>'th data point in this set. The order will never
* chance so long as no data points are added or removed from the set.
*
* @param i the <tt>i</tt>'th data point in this set
* @return the <tt>i</tt>'th data point in this set
*/
public DataPoint getDataPoint(int i)
{
return datapoints.getDataPoint(i);
}
/**
* Replaces an already existing data point with the one given.
* Any values associated with the data point, but not apart of
* it, will remain intact.
*
* @param i the <tt>i</tt>'th dataPoint to set.
* @param dp the data point to set at the specified index
*/
public void setDataPoint(int i, DataPoint dp)
{
datapoints.setDataPoint(i, dp);
}
/**
* Returns summary statistics computed in an online fashion for each numeric
* variable. This returns all summary statistics, but can be less
* numerically stable and uses more memory. <br>
* NaNs / missing values will be ignored in the statistics for each column.
*
* @param useWeights {@code true} to return the weighted statistics,
* unweighted otherwise.
* @return an array of summary statistics
*/
public OnLineStatistics[] getOnlineColumnStats(boolean useWeights)
{
OnLineStatistics[] stats = new OnLineStatistics[numNumerVals];
for(int i = 0; i < stats.length; i++)
stats[i] = new OnLineStatistics();
double totalSoW = 0.0;
/**
* We got to skip nans, count their weight in each column so that we can still fast count zeros
*/
double[] nanWeight = new double[numNumerVals];
int pos = 0;
for(Iterator<DataPoint> iter = getDataPointIterator(); iter.hasNext(); )
{
DataPoint dp = iter.next();
double weight = useWeights ? getWeight(pos++): 1;
totalSoW += weight;
Vec v = dp.getNumericalValues();
for (IndexValue iv : v)
if (Double.isNaN(iv.getValue()))//count it so we can fast count zeros right later
nanWeight[iv.getIndex()] += weight;
else
stats[iv.getIndex()].add(iv.getValue(), weight);
}
double expected = totalSoW;
//Add zero counts back in
for(int i = 0; i < stats.length; i++)
stats[i].add(0.0, expected-stats[i].getSumOfWeights()-nanWeight[i]);
return stats;
}
/**
* Returns an {@link OnLineStatistics } object that is built by observing
* what proportion of each data point contains non zero numerical values.
* A mean of 1 indicates all values were fully dense, and a mean of 0
* indicates all values were completely sparse (all zeros).
*
* @return statistics on the percent sparseness of each data point
*/
public OnLineStatistics getOnlineDenseStats()
{
OnLineStatistics stats = new OnLineStatistics();
double N = getNumNumericalVars();
for(int i = 0; i < size(); i++)
stats.add(getDataPoint(i).getNumericalValues().nnz()/N);
return stats;
}
/**
* Computes the weighted mean and variance for each column of feature
* values. This has less overhead than
* {@link #getOnlineColumnStats(boolean) } but returns less information.
*
* @return an array of the vectors containing the mean and variance for
* each column.
*/
public Vec[] getColumnMeanVariance()
{
final int d = getNumNumericalVars();
Vec[] vecs = new Vec[]
{
new DenseVector(d),
new DenseVector(d)
};
Vec means = vecs[0];
Vec stdDevs = vecs[1];
MatrixStatistics.meanVector(means, this);
MatrixStatistics.covarianceDiag(means, stdDevs, this);
return vecs;
}
/**
* Returns an iterator that will iterate over all data points in the set.
* The behavior is not defined if one attempts to modify the data set
* while being iterated.
*
* @return an iterator for the data points
*/
public Iterator<DataPoint> getDataPointIterator()
{
return datapoints.getRowIter();
}
/**
* Returns the number of data points in this data set
* @return the number of data points in this data set
*/
public int size()
{
return datapoints.size();
}
/**
*
* @return <tt>true</tt> if there are no data points in this set currently.
*/
public boolean isEmpty()
{
return size() == 0;
}
/**
* Returns the number of data points in this data set
* @return the number of data points in this data set
* @deprecated see {@link #size() }.
*/
public int getSampleSize()
{
return size();
}
/**
* Returns the number of categorical variables for each data point in the set
* @return the number of categorical variables for each data point in the set
*/
public int getNumCategoricalVars()
{
return categories.length;
}
/**
* Returns the number of numerical variables for each data point in the set
* @return the number of numerical variables for each data point in the set
*/
public int getNumNumericalVars()
{
return numNumerVals;
}
/**
* Returns the array containing the categorical data information for this data
* set. Changes to this will be reflected in the data set.
*
* @return the array of {@link CategoricalData}
*/
public CategoricalData[] getCategories()
{
return categories;
}
/**
* Creates a new dataset that is a subset of this dataset.
* @param indicies the indices of data points to insert into the new
* dataset, and will be placed in the order listed.
* @return a new dataset that is a specified subset of this dataset, and
* backed by the same values
*/
abstract protected Type getSubset(List<Integer> indicies);
/**
* This method returns a dataset that is a subset of this dataset, where
* only the rows that have no missing values are kept. The new dataset is
* backed by this dataset.
*
* @return a subset of this dataset that has all data points with missing
* features dropped
*/
public Type getMissingDropped()
{
List<Integer> hasNoMissing = new IntList();
for (int i = 0; i < size(); i++)
{
DataPoint dp = getDataPoint(i);
boolean missing = dp.getNumericalValues().countNaNs() > 0;
for(int c : dp.getCategoricalValues())
if(c < 0)
missing = true;
if(!missing)
hasNoMissing.add(i);
}
return getSubset(hasNoMissing);
}
/**
* Splits the dataset randomly into proportionally sized partitions.
*
* @param rand the source of randomness for moving data around
* @param splits any array, where the length is the number of datasets to
* create and the value of in each index is the fraction of samples that
* should be placed into that dataset. The sum of values must be less than
* or equal to 1.0
* @return a list of new datasets
*/
public List<Type> randomSplit(Random rand, double... splits)
{
if(splits.length < 1)
throw new IllegalArgumentException("Input array of split fractions must be non-empty");
IntList randOrder = new IntList(size());
ListUtils.addRange(randOrder, 0, size(), 1);
Collections.shuffle(randOrder, rand);
int[] stops = new int[splits.length];
double sum = 0;
for(int i = 0; i < splits.length; i++)
{
sum += splits[i];
if(sum >= 1.001/*some flex room for numeric issues*/)
throw new IllegalArgumentException("Input splits sum is greater than 1 by index " + i + " reaching a sum of " + sum);
stops[i] = (int) Math.round(sum*randOrder.size());
}
List<Type> datasets = new ArrayList<>(splits.length);
int prev = 0;
for(int i = 0; i < stops.length; i++)
{
List<Integer> subList = randOrder.subList(prev, stops[i]);
if(!this.rowMajor())
Collections.sort(subList);//sorting done to ensure original iter order that helps maximize performance for sparse cases
datasets.add(getSubset(subList));
prev = stops[i];
}
return datasets;
}
/**
* Splits the dataset randomly into proportionally sized partitions.
*
* @param splits any array, where the length is the number of datasets to
* create and the value of in each index is the fraction of samples that
* should be placed into that dataset. The sum of values must be less than
* or equal to 1.0
* @return a list of new datasets
*/
public List<Type> randomSplit(double... splits)
{
return randomSplit(RandomUtil.getRandom(), splits);
}
/**
* Creates <tt>folds</tt> data sets that contain data from this data set.
* The data points in each set will be random. These are meant for cross
* validation
*
* @param folds the number of cross validation sets to create. Should be greater then 1
* @param rand the source of randomness
* @return the list of data sets.
*/
public List<Type> cvSet(int folds, Random rand)
{
double[] splits = new double[folds];
Arrays.fill(splits, 1.0/folds);
return randomSplit(rand, splits);
}
/**
* Creates <tt>folds</tt> data sets that contain data from this data set.
* The data points in each set will be random. These are meant for cross
* validation
*
* @param folds the number of cross validation sets to create. Should be greater then 1
* @return the list of data sets.
*/
public List<Type> cvSet(int folds)
{
return cvSet(folds, RandomUtil.getRandom());
}
/**
* Creates a list containing the same DataPoints in this set. They are soft copies,
* in the same order as this data set. However, altering this list will have no
* effect on DataSet. Altering the DataPoints in the list will effect the
* DataPoints in this DataSet.
*
* @return a list of the DataPoints in this DataSet.
*/
public List<DataPoint> getDataPoints()
{
List<DataPoint> list = new ArrayList<>(size());
for(int i = 0; i < size(); i++)
list.add(getDataPoint(i));
return list;
}
/**
* Creates a list of the vectors values for each data point in the correct order.
* @return a list of the vectors for the data points
*/
public List<Vec> getDataVectors()
{
List<Vec> vecs = new ArrayList<>(size());
for(int i = 0; i < size(); i++)
vecs.add(getDataPoint(i).getNumericalValues());
return vecs;
}
/**
* The data set can be seen as a NxM matrix, were each row is a
* data point, and each column the values for a particular
* variable. This method grabs all the numerical values for
* a 'column' and returns it as one vector. <br>
* This vector can be altered and will not effect any of the values in the data set
*
* @param i the <tt>i</tt>'th numerical variable to obtain all values of
* @return a Vector of length {@link #size() }
*/
public Vec getNumericColumn(int i )
{
return datapoints.getNumericColumn(i);
}
/**
*
* @return the number of missing values in both numeric and categorical features
*/
public long countMissingValues()
{
long missing = 0;
if(rowMajor())
{
for (int i = 0; i < size(); i++)
{
DataPoint dp = getDataPoint(i);
missing += dp.getNumericalValues().countNaNs();
for(int c : dp.getCategoricalValues())
if(c < 0)
missing++;
}
}
else
{
for(int j = 0; j < getNumNumericalVars(); j++)
missing += datapoints.getNumericColumn(j).countNaNs();
for(int j = 0; j < getNumCategoricalVars(); j++)
missing += IntStream.of(datapoints.getCatColumn(j)).filter(z->z<0).count();
}
return missing;
}
/**
* Creates an array of column vectors for every numeric variable in this
* data set. The index of the array corresponds to the numeric feature
* index. This method is faster and more efficient than calling
* {@link #getNumericColumn(int) } when multiple columns are needed. <br>
* <br>
* Note, that the columns returned by this method may be cached and re used
* by the DataSet itself. If you need to alter the columns you should create
* your own copy of these vectors. If you know that you will be the only
* person getting a column vector from this data set, then you may safely
* alter the columns without mutating the data points themselves. However,
* future callers may or may not receive the same vector objects.
*
* @return an array of the column vectors
*/
@SuppressWarnings("unchecked")
public Vec[] getNumericColumns()
{
return getNumericColumns(Collections.EMPTY_SET);
}
/**
* Creates an array of column vectors for every numeric variable in this
* data set. The index of the array corresponds to the numeric feature
* index. This method is faster and more efficient than calling
* {@link #getNumericColumn(int) } when multiple columns are needed. <br>
* <br>
* A set of columns to skip can be provided in order to save memory if one
* does not need all the columns. <br>
* <br>
* Note, that the columns returned by this method may be cached and re used
* by the DataSet itself. If you need to alter the columns you should create
* your own copy of these vectors. If you know that you will be the only
* person getting a column vector from this data set, then you may safely
* alter the columns without mutating the data points themselves. However,
* future callers may or may not receive the same vector objects.
*
* @param skipColumns if a column's index is in this set, a {@code null}
* will be returned in the array at the column's index instead of a vector
*
* @return an array of the column vectors
*/
public Vec[] getNumericColumns(Set<Integer> skipColumns)
{
return datapoints.getNumericColumns(skipColumns);
}
/**
* Creates a matrix from the data set, where each row represent a data
* point, and each column is one of the numeric example from the data set.
* <br>
* This matrix can be altered and will not effect any of the values in the data set.
*
* @return a matrix of the data points.
*/
public Matrix getDataMatrix()
{
if(this.size() > 0 && this.getDataPoint(0).getNumericalValues().isSparse())
{
SparseVector[] vecs = new SparseVector[this.size()];
for(int i = 0; i < size(); i++)
{
Vec row = getDataPoint(i).getNumericalValues();
vecs[i] = new SparseVector(row);
}
return new SparseMatrix(vecs);
}
else
{
DenseMatrix matrix = new DenseMatrix(this.size(), this.getNumNumericalVars());
for(int i = 0; i < size(); i++)
{
Vec row = getDataPoint(i).getNumericalValues();
for(int j = 0; j < row.length(); j++)
matrix.set(i, j, row.get(j));
}
return matrix;
}
}
/**
* Creates a matrix backed by the data set, where each row is a data point
* from the dataset, and each column is one of the numeric examples from the
* data set. <br>
* Any modifications to this matrix will be reflected in the dataset. <br>
* This method has the advantage over {@link #getDataMatrix() } in that it
* does not use any additional memory and it maintains any sparsity
* information.
* @return a matrix representation of the data points
*/
public Matrix getDataMatrixView()
{
return new MatrixOfVecs(getDataVectors());
}
/**
* Returns the number of features in this data set, which is the sum of {@link #getNumCategoricalVars() } and {@link #getNumNumericalVars() }
* @return the total number of features in this data set
*/
public int getNumFeatures()
{
return getNumCategoricalVars() + getNumNumericalVars();
}
/**
* Returns a new version of this data set that is of the same type, and
* contains a different list pointing to the same data points.
* @return a shallow copy of this data set
*/
abstract public DataSet<Type> shallowClone();
/**
* Returns a new dataset of the same type to hold the same data, but is empty.
* @return a new dataset of the same type to hold the same data, but is empty.
*/
abstract public DataSet<Type> emptyClone();
/**
* Returns a new version of this data set that is of the same type, and
* contains a different listing pointing to shallow data point copies.
* Because the data point object contains the weight itself, the weight
* is not shared - while the vector and array information is. This
* allows altering the weights of the data points while preserving the
* original weights. <br>
* Altering the list or weights of the returned data set will not be
* reflected in the original. Altering the feature values will.
*
* @return a shallow copy of shallow data point copies for this data set.
*/
public DataSet getTwiceShallowClone()
{
DataSet clone = shallowClone();
for(int i = 0; i < clone.size(); i++)
{
DataPoint d = getDataPoint(i);
DataPoint sd = new DataPoint(d.getNumericalValues(), d.getCategoricalValues(), d.getCategoricalData());
clone.setDataPoint(i, sd);
}
return clone;
}
/**
* Returns statistics on the sparsity of the vectors in this data set.
* Vectors that are not considered sparse will be treated as completely
* dense, even if zero values exist in the data.
*
* @return an object containing the statistics of the vector sparsity
*/
public OnLineStatistics getSparsityStats()
{
return datapoints.getSparsityStats();
}
/**
* Sets the weight of a given datapoint within this data set.
* @param i the index to change the weight of
* @param w the new weight value.
*/
public void setWeight(int i, double w)
{
if(i >= size() || i < 0)
throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i );
else if(Double.isNaN(w) || Double.isInfinite(w) || w < 0)
throw new ArithmeticException("Invalid weight assignment of " + w);
if(w == 1 && weights == null)
return;//nothing to do, already handled implicitly
if(weights == null)//need to init?
{
weights = new double[size()];
Arrays.fill(weights, 1.0);
}
//make sure we have enouh space
if (weights.length <= i)
weights = Arrays.copyOfRange(weights, 0, Math.max(weights.length*2, i+1));
weights[i] = w;
}
/**
* Returns the weight of the specified data point
* @param i the data point index to get the weight of
* @return the weight of the requested data point
*/
public double getWeight(int i)
{
if(i >= size() || i < 0)
throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i );
if(weights == null)
return 1;
else if(weights.length <= i)
return 1;
else return weights[i];
}
/**
* This method returns the weight of each data point in a single Vector.
* When all data points have the same weight, this will return a vector that
* uses fixed memory instead of allocating a full double backed array.
*
* @return a vector that will return the weight for each data point with the
* same corresponding index.
*/
public Vec getDataWeights()
{
final int N = this.size();
if(N == 0)
return new DenseVector(0);
//assume everyone has the same weight until proven otherwise.
double weight = getWeight(0);
double[] weights_copy = null;
for(int i = 1; i < N; i++)
{
double w_i = getWeight(i);
if(weights_copy != null || weight != w_i)
{
if(weights_copy==null)//need to init storage place
{
weights_copy = new double[N];
Arrays.fill(weights_copy, 0, i, weight);
}
weights_copy[i] = w_i;
}
}
if(weights_copy == null)
return new ConstantVector(weight, size());
else
return new DenseVector(weights_copy);
}
}
| 33,316 | 34.51919 | 145 | java |
JSAT | JSAT-master/JSAT/src/jsat/DataStore.java | /*
* Copyright (C) 2018 Edward Raff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jsat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.DataPoint;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.Vec;
import jsat.math.OnLineStatistics;
import jsat.utils.IntSet;
import jsat.utils.ListUtils;
/**
*
* @author Edward Raff
*/
public interface DataStore
{
/**
* This is the default data store type that will be used whenever any new
* DataSet object is created.
*/
public static DataStore DEFAULT_STORE = new RowMajorStore();
/**
* Sets the categorical data information used in this data store
*
* @param cat_info an array of the number of categorical features, with each
* object describing their information.
*/
public void setCategoricalDataInfo(CategoricalData[] cat_info);
public CategoricalData[] getCategoricalDataInfo();
/**
* Adds the given data point to this data store. If the given data point has
* more features (numeric or categorical) than is expected, the store will
* automatically expand to accept the given features.<br>
* If you want an error to be thrown on miss-match between current and given
* data, use {@link #addDataPointCheck(jsat.classifiers.DataPoint) }.
*
*
* @param dp the data point to add
*/
public void addDataPoint(DataPoint dp);
/**
* Adds the given data point to this data store, and checks that it has the
* expected number of numeric and categorical features to be added to this
* data store.
*
* @param dp the data point to add
*/
default public void addDataPointCheck(DataPoint dp)
{
//TODO improve these error messages.
if(dp.getNumericalValues().length() != numNumeric())
throw new IllegalArgumentException("Input has incorrect number of numeric features");
int[] cat_vals = dp.getCategoricalValues();
if(cat_vals.length != numCategorical())
throw new IllegalArgumentException("Input has the incorrect number of categorical features");
for(int i = 0; i < cat_vals.length; i++)
if(getCategoricalDataInfo()[i].getNumOfCategories() <= cat_vals[i])
throw new IllegalArgumentException("Input has an invalid value for categorical feature");
addDataPoint(dp);
}
/**
* Returns the data point stored at the <tt>i</tt>'th index in this data store.
* @param i the index of the datum to get
* @return the <tt>i</tt>'th data point
*/
public DataPoint getDataPoint(int i);
/**
* This is called to indicate to the data store that we are done adding
* values. This does not mean that values can not be added in the future,
* but this allows the implementation to perform cleanup.
*/
public void finishAdding();
/**
*
* @return the number of numeric features that are contained by data in this
* store.
*/
public int numNumeric();
/**
* Sets the number of numerical features that will be stored in this datastore object
* @param d the number of numerical features (i.e., dimensions) that should be stored.
*/
public void setNumNumeric(int d);
/**
*
* @return the number of categorical features that are contained by data in
* this store.
*/
public int numCategorical();
/**
* Replaces the data point stored at the <tt>i</tt>'th index in this data store.
* @param i
* @param dp
*/
public void setDataPoint(int i, DataPoint dp);
/**
* The data set can be seen as a NxM matrix, were each row is a data point,
* and each column the values for a particular variable. This method grabs
* all the numerical values for a 'column' and returns it as one vector.
* <br>
* This vector can be altered and will not effect any of the values in the
* data set
*
* @param i the <tt>i</tt>'th numerical variable to obtain all values of
* @return a Vector of length {@link #size() }
*/
default public Vec getNumericColumn(int i)
{
if (i < 0 || i >= numNumeric())
throw new IndexOutOfBoundsException("There is no index for column " + i);
Set<Integer> toSkip = new HashSet<>(ListUtils.range(0, numNumeric()));
toSkip.remove(i);
return getNumericColumns(toSkip)[i];
}
/**
* This method grabs all the categorical values for a 'column' and returns it as an array.
* <br>
* This array can be altered and will not effect any of the values in the
* data set
*
* @param i the <tt>i</tt>'th categorical variable to obtain all values of
* @return an array
*/
public int[] getCatColumn(int i);
/**
*
* @param skipColumns if a column's index is in this set, a {@code null}
* will be returned in the array at the column's index instead of a vector
* @return
*/
public Vec[] getNumericColumns(Set<Integer> skipColumns);
default public List<DataPoint> toList()
{
List<DataPoint> list = new ArrayList<>();
for(int i = 0; i < size(); i++)
list.add(getDataPoint(i));
return list;
}
/**
*
* @return {@code true} if row-major traversal should be the preferred
* iteration order for this data store, or {@code false} if column-major
* should be preferred.
*/
default public boolean rowMajor()
{
return true;
}
public int size();
/**
* Returns statistics on the sparsity of the vectors in this data store.
* Vectors that are not considered sparse will be treated as completely
* dense, even if zero values exist in the data.
*
* @return an object containing the statistics of the vector sparsity
*/
public OnLineStatistics getSparsityStats();
public DataStore clone();
/**
* Creates a new data store that is the same type as this one, but contains
* no data points.
*
* @return a new data store that is the same type as this one, but contains
* no data points.
*/
public DataStore emptyClone();
/**
* A light weight iterator over the rows of a data set, that should be
* relatively efficient for both row-major and column-major stored data. The
* Datapoint object returned is the same data point multiple times, mutated
* by calles to the {@link Iterator#next() } method. If you want to make a
* copy of this data you should manually call the {@link DataPoint#clone() }
* method for a heavy copy, or manually call the {@link Vec#clone() } and {@link Arrays#copyOf(T[], int)
* } to do a lighter weight copy.
*
* @return an iterator over the data points, but re-uses the same objects
* for returning the datapoints.
*/
default public Iterator<DataPoint> getRowIter()
{
final int total = this.size();
final DataStore self = this;
if (this.rowMajor())
{
AtomicInteger pos = new AtomicInteger(0);
return new Iterator<DataPoint>()
{
@Override
public boolean hasNext()
{
return pos.get() < total;
}
@Override
public DataPoint next()
{
return self.getDataPoint(pos.getAndIncrement());
}
};
}
//else, sparse case
/**
* Maps row i -> non-zero columns J
*/
Map<Integer, Set<Integer>> nonZeroTable = new HashMap(this.numNumeric()+1);//If each data point had only one non-zero feature, the most things we need to track is = the number of features
Vec[] all_cols = this.getNumericColumns(Collections.EMPTY_SET);
final List<Iterator<IndexValue>> col_iters = new ArrayList<>();
for (Vec v : all_cols)
col_iters.add(v.getNonZeroIterator());
final IndexValue[] cur_col_vals = new IndexValue[this.numNumeric()];
final AtomicInteger non_null = new AtomicInteger(cur_col_vals.length);
for (int j = 0; j < cur_col_vals.length; j++)
if (col_iters.get(j).hasNext())
{
cur_col_vals[j] = col_iters.get(j).next();
int i = cur_col_vals[j].getIndex();//this is the row that this feature occured in
Set<Integer> row_i = nonZeroTable.get(i); //grab the set of features that are non-zero for this row
if(row_i == null)//update table
{
row_i = Collections.newSetFromMap(new LinkedHashMap<>());//use alinked map to maintain iteration order which is sorted by default, which will have better performance later for sparse insertions
nonZeroTable.put(i, row_i);
}
row_i.add(j); //insert feature into this row
}
else
{
cur_col_vals[j] = null;
non_null.decrementAndGet();
}
final Vec scratch = all_cols.length > 0 ? all_cols[0].clone() : new DenseVector(0);
scratch.zeroOut();
scratch.setLength(this.numNumeric());
final int[] scratch_cat = new int[this.numCategorical()];
AtomicInteger pos = new AtomicInteger(0);
final CategoricalData[] categoricalData = this.getCategoricalDataInfo();
return new Iterator<DataPoint>()
{
final Set<Integer> empty_set = Collections.EMPTY_SET;
@Override
public boolean hasNext()
{
return pos.get() < total;
}
@Override
public DataPoint next()
{
scratch.zeroOut();
int i = pos.getAndIncrement();
// for (int j = 0; j < cur_col_vals.length; j++)//slow option, not needed b/c we maintain sparse set mapping
for(int j : nonZeroTable.getOrDefault(i, empty_set))
if (cur_col_vals[j] != null && cur_col_vals[j].getIndex() <= i)
{
if (cur_col_vals[j].getIndex() == i)//on the spot, use it!
scratch.set(j, cur_col_vals[j].getValue());
//move iterator
if (col_iters.get(j).hasNext())
{
cur_col_vals[j] = col_iters.get(j).next();
int i_future = cur_col_vals[j].getIndex();
Set<Integer> row_i_future = nonZeroTable.get(i_future);
if(row_i_future == null)
{
row_i_future = Collections.newSetFromMap(new LinkedHashMap<>());//use alinked map to maintain iteration order which is sorted by default, which will have better performance later for sparse insertions
nonZeroTable.put(i_future, row_i_future);
}
row_i_future.add(j);
}
else
cur_col_vals[j] = null;
}
nonZeroTable.remove(i);
for (int j = 0; j < self.numCategorical(); j++)
{
scratch_cat[j] = self.getCatColumn(j)[i];
}
return new DataPoint(scratch, scratch_cat, categoricalData);
}
};
}
}
| 11,512 | 32.468023 | 204 | java |
JSAT | JSAT-master/JSAT/src/jsat/RowMajorStore.java | /*
* Copyright (C) 2018 Edward Raff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jsat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.DataPoint;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.SparseVector;
import jsat.linear.SubVector;
import jsat.linear.Vec;
import jsat.math.OnLineStatistics;
/**
*
* @author Edward Raff
*/
public class RowMajorStore implements DataStore
{
protected List<DataPoint> datapoints;
protected int num_numeric = 0;
protected int num_cat = 0;
protected CategoricalData[] cat_info;
/**
* Creates a new Data Store to add points to, where the number of features is not known in advance.
*/
public RowMajorStore()
{
this(0, null);
}
/**
* Creates a new Data Store with the intent for a specific number of features known ahead of time.
* @param numNumeric the number of numeric features to be in the data store
* @param cat_info the information about the categorical data
*/
public RowMajorStore(int numNumeric, CategoricalData[] cat_info)
{
this.num_numeric = numNumeric;
this.cat_info = cat_info;
this.num_cat = cat_info == null ? 0 : cat_info.length;
datapoints = new ArrayList<>();
}
public RowMajorStore(List<DataPoint> collection)
{
this(collection.get(0).numNumericalValues(), collection.get(0).getCategoricalData());
for(DataPoint dp : collection)
this.addDataPoint(dp);
}
/**
* Copy constructor
* @param toCopy the object to copy
*/
public RowMajorStore(RowMajorStore toCopy)
{
this.datapoints = new ArrayList<>(toCopy.datapoints);
if(toCopy.cat_info != null)
this.cat_info = CategoricalData.copyOf(toCopy.cat_info);
this.num_cat = toCopy.num_cat;
this.num_numeric = toCopy.numNumeric();
}
@Override
public void addDataPoint(DataPoint dp)
{
datapoints.add(dp);
num_numeric = Math.max(dp.getNumericalValues().length(), num_numeric);
num_cat = Math.max(dp.getCategoricalValues().length, num_cat);
}
@Override
public CategoricalData[] getCategoricalDataInfo()
{
return cat_info;
}
@Override
public DataPoint getDataPoint(int i)
{
return datapoints.get(i);
}
@Override
public void setDataPoint(int i, DataPoint dp)
{
datapoints.set(i, dp);
}
@Override
public void finishAdding()
{
for(int i = 0; i < datapoints.size(); i++)
{
DataPoint d = datapoints.get(i);
Vec v = d.getNumericalValues();
Vec nv = v;
//Check that the number of numeric values match up
//if short, fill with zeros
v.setLength(num_numeric);
//Check that the number of categorical values match up
//if short, fill with missing values
int[] c = d.getCategoricalValues();
int[] nc = c;
if(d.numCategoricalValues() < num_cat)
{
nc = Arrays.copyOf(c, num_cat);
for(int j = c.length; j < nc.length; j++)
nc[j] = -1;//Missing value
}
if(v != nv || c != nc)//intentionally doing equality check on objects
{
datapoints.set(i, new DataPoint(nv, nc, cat_info));
}
}
}
@Override
public int size()
{
return datapoints.size();
}
@Override
public Vec[] getNumericColumns(Set<Integer> skipColumns)
{
boolean sparse = getSparsityStats().getMean() < 0.6;
Vec[] cols = new Vec[numNumeric()];
for(int i = 0; i < cols.length; i++)
if(!skipColumns.contains(i))
{
cols[i] = sparse ? new SparseVector(size()) : new DenseVector(size());
}
for(int i = 0; i < size(); i++)
{
Vec v = getDataPoint(i).getNumericalValues();
for(IndexValue iv : v)
{
int col = iv.getIndex();
if(cols[col] != null)
cols[col].set(i, iv.getValue());
}
}
return cols;
}
@Override
public void setCategoricalDataInfo(CategoricalData[] cat_info)
{
this.cat_info = cat_info;
this.num_cat = cat_info.length;
}
@Override
public int numNumeric()
{
return num_numeric;
}
@Override
public void setNumNumeric(int d)
{
if(d < 0)
throw new RuntimeException("Can not store a negative number of features (" +d + ")");
num_numeric = d;
}
@Override
public int numCategorical()
{
return num_cat;
}
@Override
public OnLineStatistics getSparsityStats()
{
OnLineStatistics stats = new OnLineStatistics();
for(int i = 0; i < size(); i++)
{
Vec v = getDataPoint(i).getNumericalValues();
if(v.isSparse())
stats.add(v.nnz() / (double)v.length());
else
stats.add(1.0);
}
return stats;
}
@Override
public RowMajorStore clone()
{
return new RowMajorStore(this);
}
@Override
public RowMajorStore emptyClone()
{
return new RowMajorStore(num_numeric, cat_info);
}
@Override
public int[] getCatColumn(int i)
{
if (i < 0 || i >= numCategorical())
throw new IndexOutOfBoundsException("There is no index for column " + i);
int[] toRet = new int[size()];
for(int z = 0; z < size(); z++)
toRet[z] = datapoints.get(z).getCategoricalValue(i);
return toRet;
}
}
| 6,631 | 26.292181 | 104 | java |
JSAT | JSAT-master/JSAT/src/jsat/SimpleDataSet.java |
package jsat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.ClassificationDataSet;
import jsat.classifiers.DataPoint;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.SparseVector;
import jsat.linear.Vec;
import jsat.regression.RegressionDataSet;
import jsat.utils.IntList;
/**
* SimpleData Set is a basic implementation of a data set. Has no assumptions about the task that is going to be performed.
*
* @author Edward Raff
*/
public class SimpleDataSet extends DataSet<SimpleDataSet>
{
/**
* Creates a new dataset containing the given datapoints.
*
* @param datapoints the collection of data points to create a dataset from
*/
public SimpleDataSet(List<DataPoint> datapoints)
{
super(datapoints.get(0).numNumericalValues(), datapoints.get(0).getCategoricalData());
for(DataPoint dp : datapoints)
this.add(dp);
}
/**
* Creates a new dataset containing the given datapoints. The number of
* features and categorical data information will be obtained from the
* DataStore.
*
* @param datapoints the collection of data points to create a dataset from
*/
public SimpleDataSet(DataStore datapoints)
{
super(datapoints);
}
/**
* Creates a new empty data set
*
* @param numerical the number of numerical features for points in this
* dataset
* @param categories the information and number of categorical features in
* this dataset
*/
public SimpleDataSet(int numerical, CategoricalData[] categories)
{
super(numerical, categories);
}
/**
* Adds a new datapoint to this set.
* @param dp the datapoint to add
*/
public void add(DataPoint dp)
{
base_add(dp, 1.0);
}
@Override
protected SimpleDataSet getSubset(List<Integer> indicies)
{
if (this.datapoints.rowMajor())
{
SimpleDataSet newData = new SimpleDataSet(numNumerVals, categories);
for(int i : indicies)
newData.add(getDataPoint(i));
return newData;
}
else //copy columns at a time to make it faster please!
{
int new_n = indicies.size();
//when we do the vectors, due to potential sparse inputs, we want to do this faster when iterating over values that may/may-not be good and spaced oddly
Map<Integer, Integer> old_indx_to_new = new HashMap<>(indicies.size());
for(int new_i = 0; new_i < indicies.size(); new_i++)
old_indx_to_new.put(indicies.get(new_i), new_i);
DataStore new_ds = this.datapoints.emptyClone();
Iterator<DataPoint> data_iter = this.datapoints.getRowIter();
int orig_pos = 0;
while(data_iter.hasNext())
{
DataPoint dp = data_iter.next();
if(old_indx_to_new.containsKey(orig_pos))
{
DataPoint new_dp = new DataPoint(dp.getNumericalValues().clone(),Arrays.copyOf( dp.getCategoricalValues(), this.getNumCategoricalVars()), categories);
new_ds.addDataPoint(new_dp);
}
orig_pos++;
}
new_ds.finishAdding();
return new SimpleDataSet(new_ds);
}
}
/**
* Converts this dataset into one meant for classification problems. The
* given categorical feature index is removed from the data and made the
* target variable for the classification problem.
*
* @param index the classification variable index, should be in the range
* [0, {@link #getNumCategoricalVars() })
* @return a new dataset where one categorical variable is removed and made
* the target of a classification dataset
*/
public ClassificationDataSet asClassificationDataSet(int index)
{
if(index < 0)
throw new IllegalArgumentException("Index must be a non-negative value");
else if(getNumCategoricalVars() == 0)
throw new IllegalArgumentException("Dataset has no categorical variables, can not create classification dataset");
else if(index >= getNumCategoricalVars())
throw new IllegalArgumentException("Index " + index + " is larger than number of categorical features " + getNumCategoricalVars());
return new ClassificationDataSet(this, index);
}
/**
* Converts this dataset into one meant for regression problems. The
* given numeric feature index is removed from the data and made the
* target variable for the regression problem.
*
* @param index the regression variable index, should be in the range
* [0, {@link #getNumNumericalVars() })
* @return a new dataset where one numeric variable is removed and made
* the target of a regression dataset
*/
public RegressionDataSet asRegressionDataSet(int index)
{
if(index < 0)
throw new IllegalArgumentException("Index must be a non-negative value");
else if(getNumNumericalVars()== 0)
throw new IllegalArgumentException("Dataset has no numeric variables, can not create regression dataset");
else if(index >= getNumNumericalVars())
throw new IllegalArgumentException("Index " + index + " i larger than number of numeric features " + getNumNumericalVars());
RegressionDataSet rds = new RegressionDataSet(this.datapoints.toList(), index);
for(int i = 0; i < size(); i++)
rds.setWeight(i, this.getWeight(i));
return rds;
}
/**
*
* @return access to a list of the list that backs this data set. May or may
* not be backed by the original data.
*/
public List<DataPoint> getList() {
return datapoints.toList();
}
@Override
public SimpleDataSet shallowClone()
{
return new SimpleDataSet(new ArrayList<>(this.datapoints.toList()));
}
@Override
public SimpleDataSet emptyClone()
{
SimpleDataSet sds = new SimpleDataSet(numNumerVals, categories);
return sds;
}
@Override
public SimpleDataSet getTwiceShallowClone()
{
return (SimpleDataSet) super.getTwiceShallowClone();
}
}
| 6,239 | 32.368984 | 157 | java |
JSAT | JSAT-master/JSAT/src/jsat/SimpleWeightVectorModel.java | package jsat;
import jsat.linear.ConstantVector;
import jsat.linear.Vec;
/**
* This interface is for multi-class classification problems where there may be
* <i>K</i> or <i>K-1</i> weight vectors for <i>K</i> classes. For regression
* problems it is treated as <i>K = 1</i> and there should be only one weight
* vector.
*
* @author Edward Raff
*/
public interface SimpleWeightVectorModel
{
/**
* Returns the raw weight vector associated with the given class index. If
* the given class is an implicit zero vector, a {@link ConstantVector}
* object may be returned. <br>
* Do not alter the returned weight vector, as it will change the model's
* values. <br>
* <br>
* If a regression problem, only {@code index = 0} should be used
*
* @param index the class index to get the weight vector for
* @return the weight vector used for the specified class
*/
public Vec getRawWeight(int index);
/**
* Returns the bias term used with the weight vector for the given class
* index. If the model does not support or was not trained with bias
* weights, {@code 0} will be returned.<br>
* <br>
* If a regression problem, only {@code index = 0} should be used
*
* @param index the class index to get the weight vector for
* @return the bias term for the specified class
*/
public double getBias(int index);
/**
* Returns the number of weight vectors that can be returned. For binary
* classification problems the value may be 1 if only a single weight
* vector's sign is used to determine the class. For multi-class problems,
* the weight vector count includes the implicit zero vector (if one is
* being used).
* @return the number of weight vectors for which
* {@link #getRawWeight(int) } can be called.
*/
public int numWeightsVecs();
public SimpleWeightVectorModel clone();
}
| 1,977 | 34.963636 | 80 | java |
JSAT | JSAT-master/JSAT/src/jsat/SingleWeightVectorModel.java | package jsat;
import jsat.linear.Vec;
/**
* This interface is for binary classification and regression problems where the
* solution can be represented as a single weight vector.
*
* @author Edward Raff
*/
public interface SingleWeightVectorModel extends SimpleWeightVectorModel
{
/**
* Returns the only weight vector used for the model
* @return the only weight vector used for the model
*/
public Vec getRawWeight();
/**
* Returns the bias term used for the model, or 0 of the model does not
* support or was not trained with a bias term.
*
* @return the bias term for the model
*/
public double getBias();
@Override
default public Vec getRawWeight(int index)
{
if(index == 0)
return getRawWeight();
else
throw new IndexOutOfBoundsException("SingleWeightVectorModel has only a single weight vector at index 0, index " + index + " is not valid");
}
@Override
default public double getBias(int index)
{
if(index == 0)
return getBias();
else
throw new IndexOutOfBoundsException("SingleWeightVectorModel has only a single weight vector at index 0, index " + index + " is not valid");
}
@Override
default public int numWeightsVecs()
{
return 1;
}
public SingleWeightVectorModel clone();
}
| 1,358 | 24.641509 | 145 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/BaseUpdateableClassifier.java |
package jsat.classifiers;
import java.util.Collections;
import jsat.utils.IntList;
import jsat.utils.ListUtils;
/**
* A base implementation of the UpdateableClassifier.
* {@link #train(jsat.classifiers.ClassificationDataSet, java.util.concurrent.ExecutorService) } will simply call
* {@link #train(jsat.classifiers.ClassificationDataSet) }, which will call
* {@link #setUp(jsat.classifiers.CategoricalData[], int,
* jsat.classifiers.CategoricalData) } and then call
* {@link #update(jsat.classifiers.DataPoint, int) } for each data point in a
* random order.
*
* @author Edward Raff
*/
public abstract class BaseUpdateableClassifier implements UpdateableClassifier
{
private static final long serialVersionUID = 3138493999362400767L;
protected int epochs = 1;
/**
* Default constructor that does nothing
*/
public BaseUpdateableClassifier()
{
}
/**
* Copy constructor
* @param toCopy object to copy
*/
public BaseUpdateableClassifier(BaseUpdateableClassifier toCopy)
{
this.epochs = toCopy.epochs;
}
/**
* Sets the number of whole iterations through the training set that will be
* performed for training
* @param epochs the number of whole iterations through the data set
*/
public void setEpochs(int epochs)
{
if(epochs < 1)
throw new IllegalArgumentException("epochs must be a positive value");
this.epochs = epochs;
}
/**
* Returns the number of epochs used for training
* @return the number of epochs used for training
*/
public int getEpochs()
{
return epochs;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
train(dataSet);
}
@Override
public void train(ClassificationDataSet dataSet)
{
trainEpochs(dataSet, this, epochs);
}
/**
* Performs training on an updateable classifier by going over the whole
* data set in random order one observation at a time, multiple times.
*
* @param dataSet the data set to train from
* @param toTrain the classifier to train
* @param epochs the number of passes through the data set
*/
public static void trainEpochs(ClassificationDataSet dataSet, UpdateableClassifier toTrain, int epochs)
{
if(epochs < 1)
throw new IllegalArgumentException("epochs must be positive");
toTrain.setUp(dataSet.getCategories(), dataSet.getNumNumericalVars(),
dataSet.getPredicting());
IntList randomOrder = new IntList(dataSet.size());
ListUtils.addRange(randomOrder, 0, dataSet.size(), 1);
for (int epoch = 0; epoch < epochs; epoch++)
{
Collections.shuffle(randomOrder);
for (int i : randomOrder)
toTrain.update(dataSet.getDataPoint(i), dataSet.getWeight(i), dataSet.getDataPointCategory(i));
}
}
@Override
abstract public UpdateableClassifier clone();
}
| 3,058 | 28.990196 | 114 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/CategoricalData.java |
package jsat.classifiers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Edward Raff
*/
public class CategoricalData implements Cloneable, Serializable
{
private static final long serialVersionUID = 5783467611963064930L;
private int n;//Number of different categories
private List<String> catNames;
private String categoryName;
/**
*
* @param n the number of categories
*/
public CategoricalData(int n)
{
this.n = n;
catNames = new ArrayList<String>(n);
for(int i = 0; i < n; i++)
catNames.add("Option " + (i+1));
categoryName = "No Name";
}
/**
*
* @return the number of possible categories there are for this category
*/
public int getNumOfCategories()
{
return n;
}
/**
* Returns true if the given input is a valid category index for this object. Missing values (negative categories) do not count.
* @param i the index for a category in this object
* @return {@code true} if it was a valid category, {@code false} otherwise.
*/
public boolean isValidCategory(int i)
{
if (i < 0 || i >= n)
return false;
return true;
}
public String getOptionName(int i)
{
if(i < 0)
return "Missing Value";
else if(catNames != null)
return catNames.get(i);
else
return Integer.toString(i);
}
public String getCategoryName()
{
return categoryName;
}
public void setCategoryName(String categoryName)
{
this.categoryName = categoryName;
}
/**
* Sets the name of one of the value options. Duplicate names are not allowed.
* Trying to set the name of a non existent option will result in false being
* returned.
* <br>
* All names will be converted to lower case
*
* @param name the name to give
* @param i the ith index to set.
* @return true if the name was set. False if the name could not be set.
*/
public boolean setOptionName(String name, int i)
{
name = name.toLowerCase();
if(i < 0 || i >= n)
return false;
else if(catNames.contains(name))
return false;
catNames.set(i, name);
return true;
}
public CategoricalData clone()
{
CategoricalData copy = new CategoricalData(n);
if(this.catNames != null)
copy.catNames = new ArrayList<String>(this.catNames);
return copy;
}
public static CategoricalData[] copyOf(CategoricalData[] orig)
{
CategoricalData[] copy = new CategoricalData[orig.length];
for(int i = 0; i < copy.length; i++)
copy[i] = orig[i].clone();
return copy;
}
}
| 2,925 | 24.224138 | 133 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/CategoricalResults.java |
package jsat.classifiers;
import java.io.Serializable;
import java.util.Arrays;
import jsat.linear.DenseVector;
import jsat.linear.Vec;
/**
* This class represents the probabilities for each possible result classification.
* @author Edward Raff
*/
public class CategoricalResults implements Cloneable, Serializable
{
private int n;//The number of categories
private double[] probabilities;
/**
* Create a new Categorical Results, values will default to all zero.
* @param numCategories the number of options to support.
*/
public CategoricalResults(int numCategories)
{
n = numCategories;
probabilities = new double[numCategories];
}
/**
* Creates a new Categorical Result using the given array. It will use only
* a reference to the given array, and will assume the values are already
* normalized and sum to one.
* @param probabilities the array of probabilities for each outcome
*/
public CategoricalResults(double[] probabilities)
{
this.probabilities = probabilities;
n = probabilities.length;
}
/**
* Returns the number of classes that are in the result.
* @return the class count
*/
public int size()
{
return probabilities.length;
}
/**
* Sets the probability that a sample belongs to a given category.
* @param cat the category
* @param prob the value to set, may be greater then one.
* @throws IndexOutOfBoundsException if a non existent category is specified
* @throws ArithmeticException if the value set is negative or not a number
*/
public void setProb(int cat, double prob)
{
if(cat > probabilities.length)
throw new IndexOutOfBoundsException("There are only " + probabilities.length + " posibilties, " + cat + " is invalid");
else if(prob < 0 || Double.isInfinite(prob) || Double.isNaN(prob))
throw new ArithmeticException("Only zero and positive values are valid, not " + prob);
probabilities[cat] = prob;
}
/**
* Increments the stored probability that a sample belongs to a given category
* @param cat the category
* @param prob the value to increment by, may be greater then one.
* @throws IndexOutOfBoundsException if a non existent category is specified
* @throws ArithmeticException if the value set is negative or not a number
*/
public void incProb(int cat, double prob)
{
if(cat > probabilities.length)
throw new IndexOutOfBoundsException("There are only " + probabilities.length + " posibilties, " + cat + " is invalid");
else if(prob < 0 || Double.isInfinite(prob) || Double.isNaN(prob))
throw new ArithmeticException("Only zero and positive values are valid, not " + prob);
probabilities[cat] += prob;
}
/**
* Returns the category that is the most likely according to the current probability values
* @return the the most likely category
*/
public int mostLikely()
{
int top = 0;
for(int i = 1; i < probabilities.length; i++)
{
if(probabilities[i] > probabilities[top])
top = i;
}
return top;
}
/**
* Divides all the probabilities by a constant value in order to scale them
* @param c the constant to divide all probabilities by
*/
public void divideConst(double c)
{
for(int i = 0; i < probabilities.length; i++)
probabilities[i]/=c;
}
/**
* Adjusts the probabilities by dividing each value by the total sum, so
* that all values are in the range [0, 1]
*/
public void normalize()
{
double sum = 0;
for(double d : probabilities)
sum += d;
if(sum != 0)
divideConst(sum);
}
public Vec getVecView()
{
return DenseVector.toDenseVec(probabilities);
}
/**
* Returns the stored probability for the given category
* @param cat the category
* @return the associated probability
*/
public double getProb(int cat)
{
return probabilities[cat];
}
/**
* Creates a deep clone of this
* @return a deep clone
*/
@Override
public CategoricalResults clone()
{
CategoricalResults copy = new CategoricalResults(n);
copy.probabilities = Arrays.copyOf(probabilities, probabilities.length);
return copy;
}
@Override
public String toString()
{
return Arrays.toString(probabilities);
}
}
| 4,686 | 29.633987 | 131 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/ClassificationDataSet.java |
package jsat.classifiers;
import java.util.*;
import jsat.DataSet;
import jsat.DataStore;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.Vec;
import jsat.utils.IntList;
import jsat.utils.ListUtils;
/**
* ClassificationDataSet is a data set meant specifically for classification problems.
* The true class of each data point is stored separately from the data point, so that
* it can be feed into a learning algorithm and not interfere.
* <br>
* Additional functionality specific to classification problems is also available.
* @author Edward Raff
*/
public class ClassificationDataSet extends DataSet<ClassificationDataSet>
{
/**
* The categories for the predicted value
*/
protected CategoricalData predicting;
/**
* the target values
*/
protected IntList targets;
/**
* Creates a new data set for classification problems.
*
* @param dataSet the source data set
* @param predicting the categorical attribute to use as the target class
*/
public ClassificationDataSet(DataSet dataSet, int predicting)
{
this(dataSet.getDataPoints(), predicting);
//Fix up numeric names
for(int i = 0; i < getNumNumericalVars(); i++)
this.numericalVariableNames.put(i, dataSet.getNumericName(i));
for(int i = 0; i < dataSet.size(); i++)
this.setWeight(i, dataSet.getWeight(i));
}
/**
* Creates a new data set for classification problems from the given list of data points. It is assume the data points are consistent.
* @param data the list of data points for the problem.
* @param predicting the categorical attribute to use as the target class
*/
public ClassificationDataSet(List<DataPoint> data, int predicting)
{
super(data.get(0).numNumericalValues(), data.get(0).getCategoricalData());//we will fix categoricl data in a sec
//Use the first data point to set up
DataPoint tmp = data.get(0);
categories = new CategoricalData[tmp.numCategoricalValues()-1];
for(int i = 0; i < categories.length; i++)
{
categories[i] = i >= predicting ?
tmp.getCategoricalData()[i+1] : tmp.getCategoricalData()[i];
}
//re-set DataStore with fixed categories
this.datapoints.setCategoricalDataInfo(categories);
this.predicting = tmp.getCategoricalData()[predicting];
targets = new IntList(data.size());
//Fill up data
for(DataPoint dp : data)
{
int[] newCats = new int[dp.numCategoricalValues()-1];
int[] prevCats = dp.getCategoricalValues();
int k = 0;//index for the newCats
for(int i = 0; i < prevCats.length; i++)
{
if(i != predicting)
newCats[k++] = prevCats[i];
}
DataPoint newPoint = new DataPoint(dp.getNumericalValues(), newCats, categories);
datapoints.addDataPoint(newPoint);
targets.add(prevCats[predicting]);
}
}
/**
* Creates a new dataset containing the given points paired with their
* target values. Pairing is determined by the iteration order of each
* collection.<br>
* It is assumed that all options for the target variable are contained in
* the given targets list.
*
*
* @param datapoints the DataStore that will back this Data Set
* @param targets the target values to use
*/
public ClassificationDataSet(DataStore datapoints, List<Integer> targets)
{
this(datapoints, targets, new CategoricalData(targets.stream().mapToInt(i->i).max().getAsInt()+1));
}
/**
* Creates a new dataset containing the given points paired with their
* target values. Pairing is determined by the iteration order of each
* collection.
*
* @param datapoints the DataStore that will back this Data Set
* @param targets the target values to use
* @param predicting the information about the target attribute
*/
public ClassificationDataSet(DataStore datapoints, List<Integer> targets, CategoricalData predicting)
{
super(datapoints);
this.targets = new IntList(targets);
this.predicting = predicting;
}
/**
* Creates a new data set for classification problems from the given list of data points.
* The class value is paired with each data point.
*
* @param data the list of data points, paired with their class values
* @param predicting the information about the target class
*/
public ClassificationDataSet(List<DataPointPair<Integer>> data, CategoricalData predicting)
{
super(data.get(0).getVector().length(), data.get(0).getDataPoint().getCategoricalData());
this.predicting = predicting;
categories = CategoricalData.copyOf(data.get(0).getDataPoint().getCategoricalData());
targets = new IntList(data.size());
for(DataPointPair<Integer> dpp : data)
{
datapoints.addDataPoint(dpp.getDataPoint());
targets.add(dpp.getPair());
}
}
/**
* Creates a new, empty, data set for classification problems.
*
* @param numerical the number of numerical attributes for the problem
* @param categories the information about each categorical variable in the problem.
* @param predicting the information about the target class
*/
public ClassificationDataSet(int numerical, CategoricalData[] categories, CategoricalData predicting)
{
super(numerical, categories);
this.predicting = predicting;
targets = new IntList();
}
/**
* Returns the number of target classes in this classification data set. This value
* can also be obtained by calling {@link #getPredicting() getPredicting()}.
* {@link CategoricalData#getNumOfCategories() getNumOfCategories() }
* @return the number of target classes for prediction
*/
public int getClassSize()
{
return predicting.getNumOfCategories();
}
/**
* A helper method meant to be used with {@link #cvSet(int) }, this combines all
* classification data sets in a given list, but holding out the indicated list.
*
* @param list a list of data sets
* @param exception the one data set in the list NOT to combine into one file. May be negative to indicate that all portions should be combined.
* @return a combination of all the data sets in <tt>list</tt> except the one at index <tt>exception</tt>
*/
public static ClassificationDataSet comineAllBut(List<ClassificationDataSet> list, int exception)
{
int numer = list.get(0).getNumNumericalVars();
CategoricalData[] categories = list.get(0).getCategories();
CategoricalData predicting = list.get(0).getPredicting();
if(list.get(0).rowMajor())
{
ClassificationDataSet cds = new ClassificationDataSet(numer, categories, predicting);
//The list of data sets
for(int i = 0; i < list.size(); i++)
{
if(i == exception)
continue;
for(int j = 0; j < list.get(i).size(); j++)
cds.datapoints.addDataPoint(list.get(i).getDataPoint(j));
cds.targets.addAll(list.get(i).targets);
}
return cds;
}
//else, col major case
DataStore ds = list.get(0).datapoints.emptyClone();
IntList new_targets= new IntList();
//The list of data sets
for(int k = 0; k < list.size(); k++)
{
if(k == exception)
continue;
//TODO, this would probably be better by adding a merge method to DS objects.
Iterator<DataPoint> iter = list.get(k).datapoints.getRowIter();
int pos = 0;
while(iter.hasNext())
{
ds.addDataPoint(iter.next());
new_targets.add(list.get(k).getDataPointCategory(pos++));
}
}
ds.finishAdding();
return new ClassificationDataSet(ds, new_targets);
}
/**
* Returns the i'th data point from the data set
* @param i the i'th data point in this set
* @return the ith data point in this set
*/
@Override
public DataPoint getDataPoint(int i)
{
return getDataPointPair(i).getDataPoint();
}
/**
* Returns the i'th data point from the data set, paired with the integer indicating its true class
* @param i the i'th data point in this set
* @return the i'th data point from the data set, paired with the integer indicating its true class
*/
public DataPointPair<Integer> getDataPointPair(int i)
{
if(i >= size())
throw new IndexOutOfBoundsException("There are not that many samples in the data set");
return new DataPointPair<>(datapoints.getDataPoint(i), targets.getI(i));
}
@Override
public void setDataPoint(int i, DataPoint dp)
{
if(i >= size())
throw new IndexOutOfBoundsException("There are not that many samples in the data set");
datapoints.setDataPoint(i, dp);
}
/**
* Returns the integer value corresponding to the true category of the <tt>i</tt>'th data point.
* @param i the <tt>i</tt>'th data point.
* @return the integer value for the category of the <tt>i</tt>'th data point.
* @throws IndexOutOfBoundsException if <tt>i</tt> is not a valid index into the data set.
*/
public int getDataPointCategory(int i)
{
if(i >= size())
throw new IndexOutOfBoundsException("There are not that many samples in the data set: " + i);
else if(i < 0)
throw new IndexOutOfBoundsException("Can not specify negative index " + i);
return targets.get(i);
}
@Override
protected ClassificationDataSet getSubset(List<Integer> indicies)
{
if (this.datapoints.rowMajor())
{
ClassificationDataSet newData = new ClassificationDataSet(numNumerVals, categories, predicting);
for (int i : indicies)
newData.addDataPoint(getDataPoint(i), getDataPointCategory(i));
return newData;
}
else //copy columns at a time to make it faster please!
{
int new_n = indicies.size();
//when we do the vectors, due to potential sparse inputs, we want to do this faster when iterating over values that may/may-not be good and spaced oddly
Map<Integer, Integer> old_indx_to_new = new HashMap<>(indicies.size());
for(int new_i = 0; new_i < indicies.size(); new_i++)
old_indx_to_new.put(indicies.get(new_i), new_i);
DataStore new_ds = this.datapoints.emptyClone();
Iterator<DataPoint> data_iter = this.datapoints.getRowIter();
IntList new_targets = new IntList();
int orig_pos = 0;
while(data_iter.hasNext())
{
DataPoint dp = data_iter.next();
if(old_indx_to_new.containsKey(orig_pos))
{
DataPoint new_dp = new DataPoint(dp.getNumericalValues().clone(),Arrays.copyOf( dp.getCategoricalValues(), this.getNumCategoricalVars()), categories);
new_ds.addDataPoint(new_dp);
new_targets.add(this.getDataPointCategory(orig_pos));
}
orig_pos++;
}
new_ds.finishAdding();
return new ClassificationDataSet(new_ds, new_targets);
}
}
public List<ClassificationDataSet> stratSet(int folds, Random rnd)
{
ArrayList<ClassificationDataSet> cvList = new ArrayList<>();
while (cvList.size() < folds)
{
ClassificationDataSet clone = new ClassificationDataSet(numNumerVals, categories, predicting.clone());
cvList.add(clone);
}
IntList rndOrder = new IntList();
int curFold = 0;
for(int c = 0; c < getClassSize(); c++)
{
List<DataPoint> subPoints = getSamples(c);
rndOrder.clear();
ListUtils.addRange(rndOrder, 0, subPoints.size(), 1);
Collections.shuffle(rndOrder, rnd);
for(int i : rndOrder)
{
cvList.get(curFold).addDataPoint(subPoints.get(i), c);
curFold = (curFold + 1) % folds;
}
}
return cvList;
}
/**
* Creates a new data point and adds it to this data set.
* @param v the numerical values for the data point
* @param classes the categorical values for the data point
* @param classification the true class value for the data point
* @throws IllegalArgumentException if the given values are inconsistent with the data this class stores.
*/
public void addDataPoint(Vec v, int[] classes, int classification)
{
addDataPoint(v, classes, classification, 1.0);
}
private static final int[] emptyInt = new int[0];
/**
* Creates a new data point with no categorical variables and adds it to
* this data set.
* @param v the numerical values for the data point
* @param classification the true class value for the data point
* @throws IllegalArgumentException if the given values are inconsistent with the data this class stores.
*/
public void addDataPoint(Vec v, int classification)
{
addDataPoint(v, emptyInt, classification, 1.0);
}
/**
* Creates a new data point with no categorical variables and adds it to
* this data set.
* @param v the numerical values for the data point
* @param classification the true class value for the data point
* @param weight the weight value to give to the data point
* @throws IllegalArgumentException if the given values are inconsistent with the data this class stores.
*/
public void addDataPoint(Vec v, int classification, double weight)
{
addDataPoint(v, emptyInt, classification, weight);
}
/**
* Creates a new data point and add its to this data set.
* @param v the numerical values for the data point
* @param classes the categorical values for the data point
* @param classification the true class value for the data point
* @param weight the weight value to give to the data point
* @throws IllegalArgumentException if the given values are inconsistent with the data this class stores.
*/
public void addDataPoint(Vec v, int[] classes, int classification, double weight)
{
if(v.length() != numNumerVals)
throw new RuntimeException("Data point does not contain enough numerical data points");
if(classes.length != categories.length)
throw new RuntimeException("Data point does not contain enough categorical data points");
for(int i = 0; i < classes.length; i++)
if(!categories[i].isValidCategory(classes[i]) && classes[i] >= 0) // >= so that missing values (negative) are allowed
throw new IllegalArgumentException("Categoriy value given is invalid");
datapoints.addDataPointCheck(new DataPoint(v, classes, categories));
setWeight(size()-1, weight);
targets.add(classification);
}
/**
* Creates a new data point and add it
* @param dp the data point to add to this set
* @param classification the label for this data point
*/
public void addDataPoint(DataPoint dp, int classification)
{
addDataPoint(dp, classification, 1.0);
}
/**
* Creates a new data point and add it
* @param dp the data point to add to this set
* @param classification the label for this data point
* @param weight the weight for the added data point
*/
public void addDataPoint(DataPoint dp, int classification, double weight)
{
if(dp.getNumericalValues().length() != numNumerVals)
throw new RuntimeException("Data point does not contain enough numerical data points");
if(dp.getCategoricalValues().length != categories.length)
throw new RuntimeException("Data point does not contain enough categorical data points");
for(int i = 0; i < dp.getCategoricalValues().length; i++)
{
int val = dp.getCategoricalValues()[i];
if(!categories[i].isValidCategory(val) && val >= 0)
throw new RuntimeException("Categoriy value given is invalid");
}
datapoints.addDataPointCheck(dp);
targets.add(classification);
setWeight(size()-1, weight);
}
/**
* Returns the list of all examples that belong to the given category.
* @param category the category desired
* @return all given examples that belong to the given category
*/
public List<DataPoint> getSamples(int category)
{
ArrayList<DataPoint> subSet = new ArrayList<>();
for(int i = 0; i < this.targets.size(); i++)
if(this.targets.getI(i) == category)
subSet.add(datapoints.getDataPoint(i));
return subSet;
}
/**
* This method is a counter part to {@link #getNumericColumn(int) }. Instead of returning all
* values for a given attribute, all values for the attribute that are members of a specific
* class are returned.
*
* @param category the category desired
* @param n the n'th numerical variable
* @return a vector of all the values for the n'th numerical variable for the given category
*/
public Vec getSampleVariableVector(int category, int n)
{
List<DataPoint> categoryList = getSamples(category);
DenseVector vec = new DenseVector(categoryList.size());
for(int i = 0; i < vec.length(); i++)
vec.set(i, categoryList.get(i).getNumericalValues().get(n));
return vec;
}
/**
*
* @return the {@link CategoricalData} object for the variable that is to be predicted
*/
public CategoricalData getPredicting()
{
return predicting;
}
/**
* Returns the data set as a list of {@link DataPointPair}.
* Each data point is paired with it's true class value.
* Altering the data points will effect the data set.
* Altering the list will not. <br>
* The list of data points will come in the same order they would
* be retrieved in using {@link #getDataPoint(int) }
*
* @return a list of each data point paired with its class value
*/
public List<DataPointPair<Integer>> getAsDPPList()
{
List<DataPointPair<Integer>> dataPoints = new ArrayList<DataPointPair<Integer>>(size());
for(int i = 0; i < size(); i++)
dataPoints.add(new DataPointPair<Integer>(datapoints.getDataPoint(i), targets.get(i)));
return dataPoints;
}
/**
* Returns the data set as a list of {@link DataPointPair}.
* Each data point is paired with it's true class value, which is stored in a double.
* Altering the data points will effect the data set.
* Altering the list will not. <br>
* The list of data points will come in the same order they would
* be retrieved in using {@link #getDataPoint(int) }
*
* @return a list of each data point paired with its class value stored in a double
*/
public List<DataPointPair<Double>> getAsFloatDPPList()
{
List<DataPointPair<Double>> dataPoints = new ArrayList<>(size());
for(int i = 0; i < size(); i++)
dataPoints.add(new DataPointPair<>(datapoints.getDataPoint(i), (double) targets.getI(i)));
return dataPoints;
}
/**
* Computes the prior probabilities of each class, and returns an array containing the values.
* @return the array of prior probabilities
*/
public double[] getPriors()
{
double[] priors = new double[getClassSize()];
double sum = 0.0;
for(int i = 0; i < size(); i++)
{
double w = getWeight(i);
priors[targets.getI(i)] += w;
sum += w;
}
for(int i = 0; i < priors.length; i++)
priors[i] /= sum;
return priors;
}
/**
* Returns the number of data points that belong to the specified class,
* irrespective of the weights of the individual points.
*
* @param targetClass the target class
* @return how many data points belong to the given class
*/
public int classSampleCount(int targetClass)
{
int count = 0;
for(int i : targets)
if(i == targetClass)
count++;
return count;
}
@Override
public int size()
{
return datapoints.size();
}
@Override
public ClassificationDataSet shallowClone()
{
ClassificationDataSet clone = new ClassificationDataSet(numNumerVals, categories, predicting.clone());
for(int i = 0; i < size(); i++)
clone.datapoints.addDataPoint(getDataPoint(i));
clone.targets.addAll(this.targets);
if(this.weights != null)
clone.weights = Arrays.copyOf(this.weights, this.weights.length);
return clone;
}
@Override
public ClassificationDataSet emptyClone()
{
ClassificationDataSet clone = new ClassificationDataSet(numNumerVals, categories, predicting.clone());
return clone;
}
@Override
public ClassificationDataSet getTwiceShallowClone()
{
return (ClassificationDataSet) super.getTwiceShallowClone();
}
}
| 21,595 | 35.47973 | 157 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/ClassificationModelEvaluation.java |
package jsat.classifiers;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsat.DataSet;
import jsat.classifiers.evaluation.ClassificationScore;
import jsat.datatransform.DataTransformProcess;
import jsat.exceptions.UntrainedModelException;
import jsat.math.OnLineStatistics;
import jsat.utils.SystemInfo;
import jsat.utils.concurrent.ParallelUtils;
import jsat.utils.random.RandomUtil;
/**
* Provides a mechanism to quickly perform an evaluation of a model on a data set.
* This can be done with cross validation or with a testing set.
*
* @author Edward Raff
*/
public class ClassificationModelEvaluation
{
/**
* The model to evaluate
*/
private Classifier classifier;
/**
* The data set to train with.
*/
private ClassificationDataSet dataSet;
/**
* The source of threads
*/
private boolean parallel;
private double[][] confusionMatrix;
/**
* The sum of all the weights for each data point that was used in testing.
*/
private double sumOfWeights;
private long totalTrainingTime = 0, totalClassificationTime = 0;
private DataTransformProcess dtp;
private boolean keepPredictions;
private CategoricalResults[] predictions;
private int[] truths;
private double[] pointWeights;
private OnLineStatistics errorStats;
private Map<ClassificationScore, OnLineStatistics> scoreMap;
private boolean keepModels = false;
/**
* This holds models for each index that will be kept. If using a test set,
* only index 0 is used.
*/
private Classifier[] keptModels;
/**
* This holds models for each fold index that will be used for warm starts.
* If using a test set, only index 0 is used.
*/
private Classifier[] warmModels;
/**
* Constructs a new object that can perform evaluations on the model.
* The model will not be trained until evaluation time.
*
* @param classifier the model to train and evaluate
* @param dataSet the training data set.
*/
public ClassificationModelEvaluation(Classifier classifier, ClassificationDataSet dataSet)
{
this(classifier, dataSet, false);
}
/**
* Constructs a new object that can perform evaluations on the model.
* The model will not be trained until evaluation time.
*
* @param classifier the model to train and evaluate
* @param dataSet the training data set.
* @param parallel {@code true} if the training should be done using
* multiple-cores, {@code false} for single threaded.
*/
public ClassificationModelEvaluation(Classifier classifier, ClassificationDataSet dataSet, boolean parallel)
{
this.classifier = classifier;
this.dataSet = dataSet;
this.parallel = parallel;
this.dtp = new DataTransformProcess();
keepPredictions = false;
errorStats = new OnLineStatistics();
scoreMap = new LinkedHashMap<>();
}
/**
* Set this to {@code true} in order to keep the trained models after
* evaluation. They can then be retrieved used the {@link #getKeptModels() }
* methods. The default value is {@code false}.
*
* @param keepModels {@code true} to keep the trained models after
* evaluation, {@code false} to discard them.
*/
public void setKeepModels(boolean keepModels)
{
this.keepModels = keepModels;
}
/**
* This will keep the models trained when evaluating the model. The models
* can be obtained after an evaluation from {@link #getKeptModels() }.
*
* @return {@code true} if trained models will be kept after evaluation.
*/
public boolean isKeepModels()
{
return keepModels;
}
/**
* Returns the models that were kept after the last evaluation. {@code null}
* will be returned instead if {@link #isKeepModels() } returns
* {@code false}, which is the default.
*
* @return the models that were kept after the last evaluation. Or
* {@code null} if if models are not being kept.
*/
public Classifier[] getKeptModels()
{
return keptModels;
}
/**
* Sets the models that will be used for warm starting training. If using
* cross-validation, the number of models given should match the number of
* folds. If using a test set, only one model should be given.
*
* @param warmModels the models to use for warm start training
*/
public void setWarmModels(Classifier... warmModels)
{
this.warmModels = warmModels;
}
/**
* Sets the data transform process to use when performing cross validation.
* By default, no transforms are applied
* @param dtp the transformation process to clone for use during evaluation
*/
public void setDataTransformProcess(DataTransformProcess dtp)
{
this.dtp = dtp.clone();
}
/**
* Performs an evaluation of the classifier using the training data set.
* The evaluation is done by performing cross validation.
* @param folds the number of folds for cross validation
* @throws UntrainedModelException if the number of folds given is less than 2
*/
public void evaluateCrossValidation(int folds)
{
evaluateCrossValidation(folds, RandomUtil.getRandom());
}
/**
* Performs an evaluation of the classifier using the training data set.
* The evaluation is done by performing cross validation.
* @param folds the number of folds for cross validation
* @param rand the source of randomness for generating the cross validation sets
* @throws UntrainedModelException if the number of folds given is less than 2
*/
public void evaluateCrossValidation(int folds, Random rand)
{
if(folds < 2)
throw new UntrainedModelException("Model could not be evaluated because " + folds + " is < 2, and not valid for cross validation");
List<ClassificationDataSet> lcds = dataSet.cvSet(folds, rand);
evaluateCrossValidation(lcds);
}
/**
* Performs an evaluation of the classifier using the training data set,
* where the folds of the training data set are provided by the user. The
* folds do not need to be the same sizes, though it is assumed that they
* are all approximately the same size. It is the caller's responsibility to
* ensure that the folds are only from the original training data set. <br>
* <br>
* This method exists so that the user can provide very specific folds if
* they so desire. This can be useful when there is known bias in the data
* set, such as when caused by duplicate data point values. The caller can
* then manually make sure duplicate values all occur in the same fold to
* avoid over-estimating the accuracy of the model.
*
* @param lcds the training data set already split into folds
*/
public void evaluateCrossValidation(List<ClassificationDataSet> lcds)
{
List<ClassificationDataSet> trainCombinations = new ArrayList<ClassificationDataSet>(lcds.size());
for (int i = 0; i < lcds.size(); i++)
trainCombinations.add(ClassificationDataSet.comineAllBut(lcds, i));
evaluateCrossValidation(lcds, trainCombinations);
}
/**
* Note: Most people should never need to call this method. Make sure you
* understand what you are doing before you do.<br>
* <br>
* Performs an evaluation of the classifier using the training data set,
* where the folds of the training data set, and their combinations, are
* provided by the user. The folds do not need to be the same sizes, though
* it is assumed that they are all approximately the same size - and the the
* training combination corresponding to each index will be the sum of the
* folds in the other indices. It is the caller's responsibility to ensure
* that the folds are only from the original training data set. <br>
* <br>
* This method exists so that the user can provide very specific folds if
* they so desire, and when the same folds will be used multiple times.
* Doing so allows the algorithms called to take advantage of any potential
* caching of results based on the data set and avoid all possible excessive
* memory movement. (For example, {@link DataSet#getNumericColumns() } may
* get re-used and benefit from its caching)<br>
* The same behavior of this method can be obtained by calling {@link #evaluateCrossValidation(java.util.List)
* }.
*
* @param lcds training data set already split into folds
* @param trainCombinations each index contains the training data sans the
* data stored in the fold associated with that index
*/
public void evaluateCrossValidation(List<ClassificationDataSet> lcds, List<ClassificationDataSet> trainCombinations)
{
int numOfClasses = dataSet.getClassSize();
sumOfWeights = 0.0;
confusionMatrix = new double[numOfClasses][numOfClasses];
totalTrainingTime = 0;
totalClassificationTime = 0;
if(keepModels)
keptModels = new Classifier[lcds.size()];
setUpResults(dataSet.size());
int end = dataSet.size();
for (int i = lcds.size() - 1; i >= 0; i--)
{
ClassificationDataSet trainSet = trainCombinations.get(i);
ClassificationDataSet testSet = lcds.get(i);
evaluationWork(trainSet, testSet, i);
int testSize = testSet.size();
if (keepPredictions)
{
System.arraycopy(predictions, 0, predictions, end - testSize, testSize);
System.arraycopy(truths, 0, truths, end-testSize, testSize);
System.arraycopy(pointWeights, 0, pointWeights, end-testSize, testSize);
}
end -= testSize;
}
}
/**
* Performs an evaluation of the classifier using the initial data set to train, and testing on the given data set.
* @param testSet the data set to perform testing on
*/
public void evaluateTestSet(ClassificationDataSet testSet)
{
if(keepModels)
keptModels = new Classifier[1];
int numOfClasses = dataSet.getClassSize();
sumOfWeights = 0.0;
confusionMatrix = new double[numOfClasses][numOfClasses];
setUpResults(testSet.size());
totalTrainingTime = totalClassificationTime = 0;
evaluationWork(dataSet, testSet, 0);
}
private void evaluationWork(ClassificationDataSet trainSet, ClassificationDataSet testSet, int index)
{
DataTransformProcess curProcess = dtp.clone();
if (curProcess.getNumberOfTransforms() > 0)
{
trainSet = trainSet.shallowClone();
curProcess.learnApplyTransforms(trainSet);
}
final Classifier classifierToUse = classifier.clone();
long startTrain = System.currentTimeMillis();
if(warmModels != null && classifierToUse instanceof WarmClassifier)//train from the warm model
{
WarmClassifier wc = (WarmClassifier) classifierToUse;
wc.train(trainSet, warmModels[index], parallel);
}
else//do the normal thing
{
classifierToUse.train(trainSet, parallel);
}
totalTrainingTime += (System.currentTimeMillis() - startTrain);
if(keptModels != null)
keptModels[index] = classifierToUse;
CountDownLatch latch;
final double[] evalErrorStats = new double[2];//first index is correct, 2nd is total
//place to store the scores that may get updated by several threads
final Map<ClassificationScore, ClassificationScore> scoresToUpdate = new HashMap<>();
for(Entry<ClassificationScore, OnLineStatistics> entry : scoreMap.entrySet())
{
ClassificationScore score = entry.getKey().clone();
score.prepare(dataSet.getPredicting());
scoresToUpdate.put(score, score);
}
ParallelUtils.run(parallel, testSet.size(), (start, end) ->
{
//create a local set of scores to update
double localCorrect = 0;
double localSumOfWeights = 0;
long localClassificationTime = 0;
Set<ClassificationScore> localScores = new HashSet<>();
for (Entry<ClassificationScore, ClassificationScore> entry : scoresToUpdate.entrySet())
localScores.add(entry.getKey().clone());
for (int i = start; i < end; i++)
{
DataPoint dp = testSet.getDataPoint(i);
dp = curProcess.transform(dp);
double w_i = testSet.getWeight(i);
long stratClass = System.currentTimeMillis();
CategoricalResults result = classifierToUse.classify(dp);
localClassificationTime += (System.currentTimeMillis() - stratClass);
for (ClassificationScore score : localScores)
score.addResult(result, testSet.getDataPointCategory(i), w_i);
if (predictions != null)
{
predictions[i] = result;
truths[i] = testSet.getDataPointCategory(i);
pointWeights[i] = w_i;
}
final int trueCat = testSet.getDataPointCategory(i);
synchronized (confusionMatrix[trueCat])
{
confusionMatrix[trueCat][result.mostLikely()] += w_i;
}
if (trueCat == result.mostLikely())
localCorrect += w_i;
localSumOfWeights += w_i;
}
synchronized (confusionMatrix)
{
totalClassificationTime += localClassificationTime;
sumOfWeights += localSumOfWeights;
evalErrorStats[0] += localSumOfWeights - localCorrect;
evalErrorStats[1] += localSumOfWeights;
for (ClassificationScore score : localScores)
scoresToUpdate.get(score).addResults(score);
}
});
errorStats.add(evalErrorStats[0] / evalErrorStats[1]);
//accumulate score info
for (Entry<ClassificationScore, OnLineStatistics> entry : scoreMap.entrySet())
{
ClassificationScore score = entry.getKey().clone();
score.prepare(dataSet.getPredicting());
score.addResults(scoresToUpdate.get(score));
entry.getValue().add(score.getScore());
}
}
/**
* Adds a new score object that will be used as part of the evaluation when
* calling {@link #evaluateCrossValidation(int, java.util.Random) } or
* {@link #evaluateTestSet(jsat.classifiers.ClassificationDataSet) }. The
* statistics for the given score are reset on every call, and the mean /
* standard deviation comes from multiple folds in cross validation. <br>
* <br>
* The score statistics can be obtained from
* {@link #getScoreStats(ClassificationScore) }
* after one of the evaluation methods have been called.
*
* @param scorer the score method to keep track of.
*/
public void addScorer(ClassificationScore scorer)
{
scoreMap.put(scorer, new OnLineStatistics());
}
/**
* Gets the statistics associated with the given score. If the score is not
* currently in the model evaluation {@code null} will be returned. The
* object passed in does not need to be the exact same object passed to
* {@link #addScorer(ClassificationScore) },
* it only needs to be equal to the object.
*
* @param score the score type to get the result statistics
* @return the result statistics for the given score, or {@code null} if the
* score is not in th evaluation set
*/
public OnLineStatistics getScoreStats(ClassificationScore score)
{
return scoreMap.get(score);
}
/**
* Indicates whether or not the predictions made during evaluation should be
* stored with the expected value for retrieval later.
* @param keepPredictions <tt>true</tt> if space should be allocated to
* store the predictions made
*/
public void keepPredictions(boolean keepPredictions)
{
this.keepPredictions = keepPredictions;
}
/**
*
* @return <tt>true</tt> if the predictions are being stored
*/
public boolean doseStoreResults()
{
return keepPredictions;
}
/**
* If {@link #keepPredictions(boolean) } was set, this method will return
* the array storing the predictions made by the classifier during
* evaluation. These results may not be in the same order as the data set
* they came from, but the order is paired with {@link #getTruths() }
*
* @return the array of predictions, or null
*/
public CategoricalResults[] getPredictions()
{
return predictions;
}
/**
* If {@link #keepPredictions(boolean) } was set, this method will return
* the array storing the target classes that should have been predicted
* during evaluation. These results may not be in the same order as the data
* set they came from, but the order is paired with {@link #getPredictions()}
*
* @return the array of target class values, or null
*/
public int[] getTruths()
{
return truths;
}
/**
* If {@link #keepPredictions(boolean) } was set, this method will return
* the array storing the weights for each of the points that were classified
*
* @return the array of data point weights, or null
*/
public double[] getPointWeights()
{
return pointWeights;
}
public double[][] getConfusionMatrix()
{
return confusionMatrix;
}
/**
* Assuming that we are on the start of a new line, the confusion matrix will be pretty printed to {@link System#out System.out}
*/
public void prettyPrintConfusionMatrix()
{
CategoricalData predicting = dataSet.getPredicting();
int classCount = predicting.getNumOfCategories();
int nameLength = 10;
for(int i = 0; i < classCount; i++)
nameLength = Math.max(nameLength, predicting.getOptionName(i).length()+2);
final String pfx = "%-" + nameLength;//prefix
System.out.printf(pfx+"s ", "Matrix");
for(int i = 0; i < classCount-1; i++)
System.out.printf(pfx+"s ", predicting.getOptionName(i).toUpperCase());
System.out.printf(pfx+"s\n", predicting.getOptionName(classCount-1).toUpperCase());
//Now the rows that have data!
for(int i = 0; i <confusionMatrix.length; i++)
{
System.out.printf(pfx+"s ", predicting.getOptionName(i).toUpperCase());
for(int j = 0; j < classCount-1; j++)
System.out.printf(pfx+"f ", confusionMatrix[i][j]);
System.out.printf(pfx+"f\n", confusionMatrix[i][classCount-1]);
}
}
/**
* Prints out the classification information in a convenient format. If no
* additional scores were added via the
* {@link #addScorer(ClassificationScore) }
* method, nothing will be printed.
*/
public void prettyPrintClassificationScores()
{
int nameLength = 10;
for(Entry<ClassificationScore, OnLineStatistics> entry : scoreMap.entrySet())
nameLength = Math.max(nameLength, entry.getKey().getName().length()+2);
final String pfx = "%-" + nameLength;//prefix
for(Entry<ClassificationScore, OnLineStatistics> entry : scoreMap.entrySet())
{
OnLineStatistics stats = entry.getValue();
if(stats.getMax() == stats.getMin())//max = min = no varaince / 1 entry
System.out.printf(pfx+"s %-5f\n", entry.getKey().getName(), stats.getMean());
else
System.out.printf(pfx+"s %-5f (%-5f)\n", entry.getKey().getName(), stats.getMean(), stats.getStandardDeviation());
}
}
/**
* Returns the total value of the weights for data points that were classified correctly.
* @return the total value of the weights for data points that were classified correctly.
*/
public double getCorrectWeights()
{
double val = 0.0;
for(int i = 0; i < confusionMatrix.length; i++)
val += confusionMatrix[i][i];
return val;
}
/**
* Returns the total value of the weights for all data points that were tested against
* @return the total value of the weights for all data points that were tested against
*/
public double getSumOfWeights()
{
return sumOfWeights;
}
/**
* Computes the weighted error rate of the classifier. If all weights of the data
* points tested were equal, then the value returned is also the percent of data
* points that the classifier erred on.
* @return the weighted error rate of the classifier.
*/
public double getErrorRate()
{
return 1.0 - getCorrectWeights()/sumOfWeights;
}
/**
* Returns the object that keeps track of the error on
* individual evaluations. If cross-validation was used,
* it is the statistics for the errors of each fold. If
* not, it is for each time {@link #evaluateTestSet(jsat.classifiers.ClassificationDataSet) } was called.
* @return the statistics for the error of all evaluation sets
*/
public OnLineStatistics getErrorRateStats()
{
return errorStats;
}
/***
* Returns the total number of milliseconds spent training the classifier.
* @return the total number of milliseconds spent training the classifier.
*/
public long getTotalTrainingTime()
{
return totalTrainingTime;
}
/**
* Returns the total number of milliseconds spent performing classification on the testing set.
* @return the total number of milliseconds spent performing classification on the testing set.
*/
public long getTotalClassificationTime()
{
return totalClassificationTime;
}
/**
* Returns the classifier that was original given for evaluation.
* @return the classifier that was original given for evaluation.
*/
public Classifier getClassifier()
{
return classifier;
}
private void setUpResults(int resultSize)
{
if(keepPredictions)
{
predictions = new CategoricalResults[resultSize];
truths = new int[predictions.length];
pointWeights = new double[predictions.length];
}
else
{
predictions = null;
truths = null;
pointWeights = null;
}
}
}
| 23,316 | 37.732558 | 143 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/Classifier.java |
package jsat.classifiers;
import java.io.Serializable;
import jsat.exceptions.FailedToFitException;
import jsat.exceptions.ModelMismatchException;
import jsat.exceptions.UntrainedModelException;
/**
* A Classifier is used to predict the target class of new unseen data points.
*
* @author Edward Raff
*/
public interface Classifier extends Cloneable, Serializable
{
/**
* Performs classification on the given data point.
* @param data the data point to classify
* @return the results of the classification.
* @throws UntrainedModelException if the method is called before the model has been trained
* @throws ModelMismatchException if the given data point is incompatible with the model
*/
public CategoricalResults classify(DataPoint data);
/**
* Trains the classifier and constructs a model for classification using the
* given data set. If the training method knows how, it will used the
* <tt>threadPool</tt> to conduct training in parallel. This method will
* block until the training has completed.
*
* @param dataSet the data set to train on
* @param parallel {@code true} if multiple threads should be used to train
* the model. {@code false} if it should be done in a single threaded
* manner.
* @throws FailedToFitException if the model is unable to be constructed for some reason
*/
public void train(ClassificationDataSet dataSet, boolean parallel);
/**
* Trains the classifier and constructs a model for classification using the
* given data set.
*
* @param dataSet the data set to train on
* @throws FailedToFitException if the model is unable to be constructed for some reason
*/
default public void train(ClassificationDataSet dataSet)
{
Classifier.this.train(dataSet, false);
}
/**
* Indicates whether the model knows how to train using weighted data points. If it
* does, the model will train assuming the weights. The values returned by this
* method may change depending on the parameters set for the model.
* @return <tt>true</tt> if the model supports weighted data, <tt>false</tt> otherwise
*/
public boolean supportsWeightedData();
public Classifier clone();
}
| 2,312 | 37.55 | 96 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/DDAG.java | package jsat.classifiers;
import java.util.PriorityQueue;
/**
* Decision Directed Acyclic Graph (DDAG) classifier. DDAG extends
* binary decision classifiers into multi-class decision classifiers. Unlike
* {@link OneVSOne}, DDAG results are hard classification decisions, and will
* not give probabilistic estimates. Accuracy is often very similar, but DDAG
* classification speed can be significantly faster, as it does not evaluate all
* possible combinations of classifiers.
*
* @author Edward Raff
*/
public class DDAG extends OneVSOne
{
private static final long serialVersionUID = -9109002614319657144L;
/**
* Creates a new DDAG classifier to extend a binary classifier to handle multi-class problems.
* @param baseClassifier the binary classifier to extend
* @param concurrentTrain <tt>true</tt> to have training of individual
* classifiers occur in parallel, <tt>false</tt> to have them use their
* native parallel training method.
*/
public DDAG(Classifier baseClassifier, boolean concurrentTrain)
{
super(baseClassifier, concurrentTrain);
}
/**
* Creates a new DDAG classifier to extend a binary classifier to handle multi-class problems.
* @param baseClassifier the binary classifier to extend
*/
public DDAG(Classifier baseClassifier)
{
super(baseClassifier);
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());
//Use a priority que so that we always pick the two lowest value class labels, makes indexing into the oneVsOne array simple
PriorityQueue<Integer> options = new PriorityQueue<Integer>(predicting.getNumOfCategories());
for(int i = 0; i < cr.size(); i++)
options.add(i);
CategoricalResults subRes;
int c1, c2;
//We will now loop through and repeatedly pick two combinations, and eliminate the loser, until there is one winer
while(options.size() > 1)
{
c1 = options.poll();
c2 = options.poll();
subRes = oneVone[c1][c2-c1-1].classify(data);
if(subRes.mostLikely() == 0)//c1 wins, c2 no longer a candidate
options.add(c1);
else//c2 wins, c1 no onger a candidate
options.add(c2);
}
cr.setProb(options.peek(), 1.0);
return cr;
}
@Override
public DDAG clone()
{
DDAG clone = new DDAG(baseClassifier.clone(), isConcurrentTraining());
if (oneVone != null)
{
clone.oneVone = new Classifier[oneVone.length][];
for (int i = 0; i < oneVone.length; i++)
{
clone.oneVone[i] = new Classifier[oneVone[i].length];
for (int j = 0; j < oneVone[i].length; j++)
clone.oneVone[i][j] = oneVone[i][j].clone();
}
}
if(predicting != null)
clone.predicting = predicting.clone();
return clone;
}
}
| 3,185 | 32.893617 | 132 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/DataPoint.java |
package jsat.classifiers;
import java.io.Serializable;
import java.util.Arrays;
import jsat.linear.Vec;
/**
* This is the general class object for representing a singular data point in a data set.
* Every data point is made up of either categorical variables, numerical variables,
* or a combination of the two.
*
* @author Edward Raff
*/
public class DataPoint implements Cloneable, Serializable
{
private static final long serialVersionUID = -1363327591317639945L;
protected Vec numericalValues;
protected int[] categoricalValues;
protected CategoricalData[] categoricalData;
private static final int[] emptyInt = new int[0];
private static final CategoricalData[] emptyData = new CategoricalData[0];
/**
* Creates a new data point
*
* @param numericalValues a vector containing the numerical values for this data point
* @param categoricalValues an array of the category values for this data point
* @param categoricalData an array of the category information of this data point
*/
public DataPoint(Vec numericalValues, int[] categoricalValues, CategoricalData[] categoricalData)
{
this.numericalValues = numericalValues;
this.categoricalValues = categoricalValues;
this.categoricalData = categoricalData;
}
/**
* Creates a new data point that has no categorical variables
*
* @param numericalValues a vector containing the numerical values for this data point
*/
public DataPoint(Vec numericalValues)
{
this(numericalValues, emptyInt, emptyData);
}
/**
* Returns true if this data point contains any categorical variables, false otherwise.
* @return true if this data point contains any categorical variables, false otherwise.
*/
public boolean containsCategoricalData()
{
return categoricalValues.length > 0;
}
/**
* Returns the vector containing the numerical values. Altering this
* vector will effect this data point. If changes are going to be
* made, a clone of the vector should be made by the caller.
* @return the vector containing the numerical values.
*/
public Vec getNumericalValues()
{
return numericalValues;
}
/**
* Returns true if the data point contains any numerical variables, false otherwise.
* @return true if the data point contains any numerical variables, false otherwise.
*/
public boolean containsNumericalData()
{
return numericalValues != null && numericalValues.length() > 0;
}
/**
* Returns the number of numerical variables in this data point.
* @return the number of numerical variables in this data point.
*/
public int numNumericalValues()
{
return numericalValues == null ? 0 : numericalValues.length();
}
/**
* Returns the array of values for each category. Altering
* this array will effect this data point. If changes are
* going to be made, a clone of the array should be made
* by the caller.
* @return the array of values for each category.
*/
public int[] getCategoricalValues()
{
return categoricalValues;
}
/**
* Returns the number of categorical variables in this data point.
* @return the number of categorical variables in this data point.
*/
public int numCategoricalValues()
{
return categoricalValues.length;
}
/**
*
* @param i the i'th categorical variable
* @return the value of the i'th categorical variable
*
*/
public int getCategoricalValue(int i)
{
return categoricalValues[i];
}
/**
* Returns the array of Categorical Data information
* @return the array of Categorical Data information
*/
public CategoricalData[] getCategoricalData()
{
return categoricalData;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
if(containsNumericalData())
{
sb.append("Numerical: ");
sb.append(numericalValues.toString());
}
if(containsCategoricalData())
{
sb.append(" Categorical: ");
for(int i = 0; i < categoricalValues.length; i++)
{
sb.append(categoricalData[i].getOptionName(categoricalValues[i]));
sb.append(",");
}
}
return sb.toString();
}
/**
* Creates a deep clone of this data point, such that altering either data point does not effect the other one.
* @return a deep clone of this data point.
*/
public DataPoint clone()
{
return new DataPoint(numericalValues.clone(),
Arrays.copyOf(categoricalValues, categoricalValues.length),
CategoricalData.copyOf(categoricalData));
}
}
| 5,025 | 29.834356 | 116 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/DataPointPair.java |
package jsat.classifiers;
import java.io.Serializable;
import jsat.linear.Vec;
/**
*
* This class exists so that any data point can be arbitrarily paired with some value
* @author Edward Raff
*/
public class DataPointPair<P> implements Serializable
{
private static final long serialVersionUID = 5091308998873225566L;
DataPoint dataPoint;
P pair;
public DataPointPair(DataPoint dataPoint, P pair)
{
this.dataPoint = dataPoint;
this.pair = pair;
}
public void setDataPoint(DataPoint dataPoint)
{
this.dataPoint = dataPoint;
}
public void setPair(P pair)
{
this.pair = pair;
}
public DataPoint getDataPoint()
{
return dataPoint;
}
public P getPair()
{
return pair;
}
/**
* The same as calling {@link DataPoint#getNumericalValues() } on {@link #getDataPoint() }.
* @return the Vec related to the data point in this pair.
*/
public Vec getVector()
{
return dataPoint.getNumericalValues();
}
}
| 1,061 | 18.666667 | 95 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/MajorityVote.java |
package jsat.classifiers;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
* The Majority Vote classifier is a simple ensemble classifier. Given a list of base classifiers,
* it will sum the most likely votes from each base classifier and return a result based on the
* majority votes. It does not take into account the confidence of the votes.
*
* @author Edward Raff
*/
public class MajorityVote implements Classifier
{
private static final long serialVersionUID = 7945429768861275845L;
private Classifier[] voters;
/**
* Creates a new Majority Vote classifier using the given voters. If already trained, the
* Majority Vote classifier can be used immediately. The MajorityVote does not make
* copies of the given classifiers. <br>
* <tt>null</tt> values in the array will have no vote.
*
* @param voters the array of voters to use
*/
public MajorityVote(Classifier... voters)
{
this.voters = voters;
}
/**
* Creates a new Majority Vote classifier using the given voters. If already trained, the
* Majority Vote classifier can be used immediately. The MajorityVote does not make
* copies of the given classifiers. <br>
* <tt>null</tt> values in the array will have no vote.
*
* @param voters the list of voters to use
*/
public MajorityVote(List<Classifier> voters)
{
this.voters = voters.toArray(new Classifier[0]);
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults toReturn = null;
for (Classifier classifier : voters)
if (classifier != null)
if (toReturn == null)
{
toReturn = classifier.classify(data);
//Instead of allocating a new catResult, reuse the given one. Set the non likely to zero, and most to 1.
for (int i = 0; i < toReturn.size(); i++)
if (i != toReturn.mostLikely())
toReturn.setProb(i, 0);
else
toReturn.setProb(i, 1.0);
}
else
{
CategoricalResults vote = classifier.classify(data);
for (int i = 0; i < toReturn.size(); i++)
toReturn.incProb(vote.mostLikely(), 1.0);
}
toReturn.normalize();
return toReturn;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
for(Classifier classifier : voters)
classifier.train(dataSet, parallel);
}
@Override
public void train(ClassificationDataSet dataSet)
{
for(Classifier classifier : voters)
classifier.train(dataSet);
}
@Override
public boolean supportsWeightedData()
{
return false;
}
@Override
public Classifier clone()
{
Classifier[] votersClone = new Classifier[this.voters.length];
for(int i = 0; i < voters.length; i++)
if(voters[i] != null)
votersClone[i] = voters[i].clone();
return new MajorityVote(voters);
}
}
| 3,283 | 30.27619 | 125 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/OneVSAll.java |
package jsat.classifiers;
import java.util.ArrayList;
import java.util.List;
import jsat.classifiers.calibration.BinaryScoreClassifier;
import jsat.parameters.Parameter.ParameterHolder;
import jsat.parameters.Parameterized;
import jsat.utils.concurrent.ParallelUtils;
/**
* This classifier turns any classifier, specifically binary classifiers, into
* multi-class classifiers. For a problem with <i>k</i> target classes, OneVsALl
* will create <i>k</i> different classifiers. Each one is a reducing of one
* class against all other classes. Then all <i>k</i> classifiers's results are
* summed to produce a final classifier
* <br><br>
* If the base learner is an instance of {@link BinaryScoreClassifier}, then the
* winning class label will be the associated classifier that produced the
* highest score.
*
* @author Edward Raff
*/
public class OneVSAll implements Classifier, Parameterized
{
private static final long serialVersionUID = -326668337438092217L;
private Classifier[] oneVsAlls;
@ParameterHolder
private Classifier baseClassifier;
private CategoricalData predicting;
private boolean concurrentTraining;
private boolean useScoreIfAvailable = true;
/**
* Creates a new One VS All classifier.
*
* @param baseClassifier the base classifier to replicate
* @see #setConcurrentTraining(boolean)
*/
public OneVSAll(Classifier baseClassifier)
{
this(baseClassifier, true);
}
/**
* Creates a new One VS All classifier.
*
* @param baseClassifier the base classifier to replicate
* @param concurrentTraining controls whether or not classifiers are trained
* simultaneously or using sequentially using their
* {@link Classifier#train(jsat.classifiers.ClassificationDataSet, java.util.concurrent.ExecutorService) } method.
* @see #setConcurrentTraining(boolean)
*/
public OneVSAll(Classifier baseClassifier, boolean concurrentTraining)
{
this.baseClassifier = baseClassifier;
this.concurrentTraining = concurrentTraining;
}
/**
* Controls what method of parallel training to use when
* {@link #train(jsat.classifiers.ClassificationDataSet, java.util.concurrent.ExecutorService) }
* is called. If set to true, each of the <i>k</i> classifiers will be trained in parallel, using
* their serial algorithms. If set to false, the <i>k</i> classifiers will be trained sequentially,
* calling the {@link Classifier#train(jsat.classifiers.ClassificationDataSet, java.util.concurrent.ExecutorService) }
* for each classifier. <br>
* <br>
* This should be set to true for classifiers that do not support parallel training.<br>
* Setting this to true also uses <i>k</i> times the memory, since each classifier is being created and trained at the same time.
* @param concurrentTraining whether or not to train the classifiers in parallel
*/
public void setConcurrentTraining(boolean concurrentTraining)
{
this.concurrentTraining = concurrentTraining;
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());
if(useScoreIfAvailable && oneVsAlls[0] instanceof BinaryScoreClassifier)
{
int maxIndx = 0;
double maxScore = Double.NEGATIVE_INFINITY;
for(int i = 0; i < predicting.getNumOfCategories(); i++)
{
double score = -( (BinaryScoreClassifier)oneVsAlls[i]).getScore(data);
if(score > maxScore)
{
maxIndx = i;
maxScore =score;
}
}
cr.setProb(maxIndx, 1);
}
else
{
for(int i = 0; i < predicting.getNumOfCategories(); i++)
{
CategoricalResults oneVsAllCR = oneVsAlls[i].classify(data);
double tmp = oneVsAllCR.getProb(0);
if(tmp > 0)
cr.setProb(i, tmp);
}
cr.normalize();
}
return cr;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
oneVsAlls = new Classifier[dataSet.getClassSize()];
predicting = dataSet.getPredicting();
List<List<DataPoint>> categorized = new ArrayList<List<DataPoint>>();
for(int i = 0; i < oneVsAlls.length; i++)
{
List<DataPoint> tmp = dataSet.getSamples(i);
ArrayList<DataPoint> oneCat = new ArrayList<DataPoint>(tmp.size());
oneCat.addAll(tmp);
categorized.add(oneCat);
}
int numer = dataSet.getNumNumericalVars();
CategoricalData[] categories = dataSet.getCategories();
ParallelUtils.range(0, oneVsAlls.length, parallel && concurrentTraining).forEach( i ->
{
final ClassificationDataSet cds =
new ClassificationDataSet(numer, categories, new CategoricalData(2));
for(DataPoint dp : categorized.get(i))//add the ones
cds.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), 0);
//Add all the 'others'
for(int j = 0; j < categorized.size(); j++)
if(j != i)
for(DataPoint dp: categorized.get(j))
cds.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), 1);
oneVsAlls[i] = baseClassifier.clone();
if(concurrentTraining)//we are training all models in parallel, so tell each model to do single-thread
oneVsAlls[i].train(cds, false);
else
oneVsAlls[i].train(cds, parallel);
});
}
@Override
public OneVSAll clone()
{
OneVSAll clone = new OneVSAll(baseClassifier.clone(), concurrentTraining);
if(this.predicting != null)
clone.predicting = this.predicting.clone();
if(this.oneVsAlls != null)
{
clone.oneVsAlls = new Classifier[this.oneVsAlls.length];
for(int i = 0; i < oneVsAlls.length; i++)
if(this.oneVsAlls[i] != null)
clone.oneVsAlls[i] = this.oneVsAlls[i].clone();
}
return clone;
}
@Override
public boolean supportsWeightedData()
{
return baseClassifier.supportsWeightedData();
}
}
| 6,628 | 36.241573 | 134 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/OneVSOne.java | package jsat.classifiers;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsat.parameters.Parameter.ParameterHolder;
import jsat.parameters.Parameterized;
import jsat.utils.FakeExecutor;
import jsat.utils.SystemInfo;
/**
* A One VS One classifier extends binary decision classifiers into multi-class
* decision classifiers. This is done by creating a binary-classification
* problem for every possible pair of classes, and then classifying by taking
* the result of all possible combinations and choosing the class that got the
* most results. This allows for a soft decision result, however, it often
* proves to be a meaningless soft boundary.
*
* @author Edward Raff
*/
public class OneVSOne implements Classifier, Parameterized
{
private static final long serialVersionUID = 733202830281869416L;
/**
* Main binary classifier
*/
@ParameterHolder
protected Classifier baseClassifier;
/**
* Uper-diagonal matrix of classifiers sans the first index since a
* classifier vs itself is useless. First index is the first dimensions is
* the first class, 2nd index + the value of the first + 1 is the opponent
* class
*/
protected Classifier[][] oneVone;
private boolean concurrentTrain;
protected CategoricalData predicting;
/**
* Creates a new One-vs-One classifier
* @param baseClassifier the binary classifier to extend
*/
public OneVSOne(Classifier baseClassifier)
{
this(baseClassifier, false);
}
/**
* Creates a new One-vs-One classifier
* @param baseClassifier the binary classifier to extend
* @param concurrentTrain <tt>true</tt> to have training of individual
* classifiers occur in parallel, <tt>false</tt> to have them use their
* native parallel training method.
*/
public OneVSOne(Classifier baseClassifier, boolean concurrentTrain)
{
this.baseClassifier = baseClassifier;
this.concurrentTrain = concurrentTrain;
}
/**
* Controls whether or not training of the several classifiers occurs concurrently or sequentually.
* @param concurrentTrain <tt>true</tt> to have training of individual
* classifiers occur in parallel, <tt>false</tt> to have them use their
* native parallel training method.
*/
public void setConcurrentTraining(boolean concurrentTrain)
{
this.concurrentTrain = concurrentTrain;
}
/**
*
* @return <tt>true</tt> if training of individual
* classifiers occur in parallel, <tt>false</tt> they use their
* native parallel training method.
*/
public boolean isConcurrentTraining()
{
return concurrentTrain;
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());
for (int i = 0; i < oneVone.length; i++)
{
for (int j = 0; j < oneVone[i].length; j++)
{
CategoricalResults subRes = oneVone[i][j].classify(data);
int mostLikely = subRes.mostLikely();
if(mostLikely == 0)
cr.incProb(i, 1.0);
else
cr.incProb(i+j+1, 1.0);
}
}
cr.normalize();
return cr;
}
@Override
public void train(final ClassificationDataSet dataSet, final boolean parallel)
{
oneVone = new Classifier[dataSet.getClassSize()][];
List<List<DataPoint>> dataByCategory = new ArrayList<>(dataSet.getClassSize());
for(int i = 0; i < dataSet.getClassSize(); i++)
dataByCategory.add(dataSet.getSamples(i));
final CountDownLatch latch = new CountDownLatch(oneVone.length*(oneVone.length-1)/2);
ExecutorService threadPool = parallel ? Executors.newFixedThreadPool(SystemInfo.LogicalCores) : new FakeExecutor();
for(int i = 0; i < oneVone.length; i++)
{
oneVone[i] = new Classifier[oneVone.length-i-1];
for(int j = 0; j < oneVone.length-i-1; j++)
{
final Classifier curClassifier = baseClassifier.clone();
oneVone[i][j] = curClassifier;
final int otherClass = j+i+1;
CategoricalData subPred = new CategoricalData(2);
subPred.setOptionName(dataSet.getPredicting().getOptionName(i), 0);
subPred.setOptionName(dataSet.getPredicting().getOptionName(otherClass), 1);
final ClassificationDataSet subDataSet = new ClassificationDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories(), subPred);
//Fill sub data set with the two classes
for(DataPoint dp : dataByCategory.get(i))
subDataSet.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), 0);
for(DataPoint dp : dataByCategory.get(otherClass))
subDataSet.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), 1);
if(!concurrentTrain)
{
curClassifier.train(subDataSet, parallel);
continue;
}
//Else, concurrent
threadPool.submit(() ->
{
curClassifier.train(subDataSet);
latch.countDown();
});
}
}
if (concurrentTrain)
try
{
latch.await();
}
catch (InterruptedException ex)
{
Logger.getLogger(OneVSOne.class.getName()).log(Level.SEVERE, null, ex);
}
predicting = dataSet.getPredicting();
threadPool.shutdownNow();
}
@Override
public boolean supportsWeightedData()
{
return baseClassifier.supportsWeightedData();
}
@Override
public OneVSOne clone()
{
OneVSOne clone = new OneVSOne(baseClassifier.clone(), concurrentTrain);
if (oneVone != null)
{
clone.oneVone = new Classifier[oneVone.length][];
for (int i = 0; i < oneVone.length; i++)
{
clone.oneVone[i] = new Classifier[oneVone[i].length];
for (int j = 0; j < oneVone[i].length; j++)
clone.oneVone[i][j] = oneVone[i][j].clone();
}
}
if(predicting != null)
clone.predicting = predicting.clone();
return clone;
}
}
| 6,913 | 33.57 | 149 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/PriorClassifier.java | package jsat.classifiers;
import java.util.concurrent.ExecutorService;
import jsat.exceptions.UntrainedModelException;
/**
* A Naive classifier that simply returns the prior probabilities as the
* classification decision.
*
* @author Edward Raff
*/
public class PriorClassifier implements Classifier
{
private static final long serialVersionUID = 7763388716880766538L;
private CategoricalResults cr;
/**
* Creates a new PriorClassifeir
*/
public PriorClassifier()
{
}
/**
* Creates a new Prior Classifier that is given the results it should be
* returning
*
* @param cr the prior probabilities for classification
*/
public PriorClassifier(CategoricalResults cr)
{
this.cr = cr;
}
@Override
public CategoricalResults classify(DataPoint data)
{
if(cr == null)
throw new UntrainedModelException("PriorClassifier has not been trained");
return cr;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
train(dataSet);
}
@Override
public void train(ClassificationDataSet dataSet)
{
cr = new CategoricalResults(dataSet.getPredicting().getNumOfCategories());
for(int i = 0; i < dataSet.size(); i++)
cr.incProb(dataSet.getDataPointCategory(i), dataSet.getWeight(i));
cr.normalize();
}
@Override
public boolean supportsWeightedData()
{
return true;
}
@Override
public Classifier clone()
{
PriorClassifier clone = new PriorClassifier();
if(this.cr != null)
clone.cr = this.cr.clone();
return clone;
}
}
| 1,713 | 22.162162 | 86 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/RegressorToClassifier.java | package jsat.classifiers;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import jsat.classifiers.calibration.BinaryScoreClassifier;
import jsat.parameters.Parameter;
import jsat.parameters.Parameterized;
import jsat.regression.RegressionDataSet;
import jsat.regression.Regressor;
/**
* This meta algorithm wraps a {@link Regressor} to perform binary
* classification. This is done my labeling class 0 data points as "-1" and
* class 1 points as "1". The sign of the outputs then determines the class. Not
* all regression algorithms will work well in this setting, and standard
* parameter values need to change. <br>
* The parameter values returned are exactly those provided by the given
* regressor, or an empty list if the regressor does not implement
* {@link Parameterized}
*
* @author Edward Raff
*/
public class RegressorToClassifier implements BinaryScoreClassifier, Parameterized
{
private static final long serialVersionUID = -2607433019826385335L;
private Regressor regressor;
/**
* Creates a new Binary Classifier by using the given regressor
* @param regressor the regressor to wrap as a binary classifier
*/
public RegressorToClassifier(Regressor regressor)
{
this.regressor = regressor;
}
@Override
public double getScore(DataPoint dp)
{
return regressor.regress(dp);
}
@Override
public RegressorToClassifier clone()
{
return new RegressorToClassifier(regressor.clone());
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(2);
if(getScore(data) > 0)
cr.setProb(1, 1.0);
else
cr.setProb(0, 1.0);
return cr;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
RegressionDataSet rds = getRegressionDataSet(dataSet);
regressor.train(rds, parallel);
}
@Override
public void train(ClassificationDataSet dataSet)
{
RegressionDataSet rds = getRegressionDataSet(dataSet);
regressor.train(rds);
}
@Override
public boolean supportsWeightedData()
{
return regressor.supportsWeightedData();
}
private RegressionDataSet getRegressionDataSet(ClassificationDataSet dataSet)
{
RegressionDataSet rds = new RegressionDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories());
for(int i = 0; i < dataSet.size(); i++)
rds.addDataPoint(dataSet.getDataPoint(i), dataSet.getDataPointCategory(i)*2-1);
return rds;
}
@Override
public List<Parameter> getParameters()
{
if(regressor instanceof Parameterized)
return ((Parameterized)regressor).getParameters();
else
return Collections.EMPTY_LIST;
}
@Override
public Parameter getParameter(String paramName)
{
if(regressor instanceof Parameterized)
return ((Parameterized)regressor).getParameter(paramName);
else
return null;
}
}
| 3,172 | 27.845455 | 110 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/Rocchio.java |
package jsat.classifiers;
import java.util.*;
import java.util.concurrent.atomic.DoubleAdder;
import jsat.exceptions.FailedToFitException;
import jsat.linear.DenseVector;
import jsat.linear.Vec;
import jsat.linear.distancemetrics.*;
import jsat.utils.DoubleList;
import jsat.utils.concurrent.ParallelUtils;
/**
*
* @author Edward Raff
*/
public class Rocchio implements Classifier
{
private static final long serialVersionUID = 889524967453326516L;
private List<Vec> rocVecs;
private final DistanceMetric dm;
private List<Double> rocCache;
public Rocchio()
{
this(new EuclideanDistance());
}
public Rocchio(DistanceMetric dm)
{
this.dm = dm;
rocVecs = null;
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(rocVecs.size());
double sum = 0;
Vec target = data.getNumericalValues();
List<Double> qi = dm.getQueryInfo(target);
//Record the average for each class
for(int i = 0; i < rocVecs.size(); i++)
{
double distance = dm.dist(i, target, qi, rocVecs, rocCache);
sum += distance;
cr.setProb(i, distance);
}
//now scale, set them all to 1-distance/sumOfDistances. We will call that out probablity
for(int i = 0; i < rocVecs.size(); i++)
cr.setProb(i, 1.0 - cr.getProb(i) / sum);
return cr;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
if(dataSet.getNumCategoricalVars() != 0)
throw new FailedToFitException("Classifier requires all variables be numerical");
int C = dataSet.getClassSize();
rocVecs = new ArrayList<>(C);
TrainableDistanceMetric.trainIfNeeded(dm, dataSet, parallel);
//dimensions
int d = dataSet.getNumNumericalVars();
//Set up a bunch of threads to add vectors together in the background
DoubleAdder totalWeight = new DoubleAdder();
rocVecs = new ArrayList<>(Arrays.asList(ParallelUtils.run(parallel, dataSet.size(),
//partial sum for each class
(int start, int end) ->
{
//find class vec sums
Vec[] local_roc = new Vec[C];
for(int i = 0; i < C; i++)
local_roc[i] = new DenseVector(d);
for(int i = start; i < end; i++)
{
double w = dataSet.getWeight(i);
local_roc[dataSet.getDataPointCategory(i)].mutableAdd(w, dataSet.getDataPoint(i).getNumericalValues());
totalWeight.add(w);
}
return local_roc;
},
//reduce down to a final sum per class
(Vec[] t, Vec[] u) ->
{
for(int i = 0; i < t.length; i++)
t[i].mutableAdd(u[i]);
return t;
})));
//Normalize each vec so we have the correct values in the end
double[] priors = dataSet.getPriors();
for(int i = 0; i < C; i++)
rocVecs.get(i).mutableDivide(totalWeight.sum()*priors[i]);
//prep cache for inference
rocCache = dm.getAccelerationCache(rocVecs, parallel);
}
@Override
public boolean supportsWeightedData()
{
return true;
}
@Override
public Rocchio clone()
{
Rocchio copy = new Rocchio(this.dm);
if(this.rocVecs != null)
{
copy.rocVecs = new ArrayList<>(this.rocVecs.size());
for(Vec v : this.rocVecs)
copy.rocVecs.add(v.clone());
copy.rocCache = new DoubleList(rocCache);
}
return copy;
}
}
| 3,775 | 28.5 | 119 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/UpdateableClassifier.java | package jsat.classifiers;
import jsat.exceptions.UntrainedModelException;
/**
* UpdateableClassifier is an interface for one type of Online learner. The main
* characteristic of an online learning is that new example points can be added
* incremental after the classifier was initially trained, or as part of its
* initial training. <br>
* Some Online learners behave differently in when they are updated. The
* UpdateableClassifier is an online learner that specifically only performs
* additional learning when a new example is provided via the
* {@link #update(jsat.classifiers.DataPoint, int) } method.
* <br>
* The standard behavior for an Updateable Classifier is that the user first
* calls {@link #trainC(jsat.classifiers.ClassificationDataSet) } to first train
* the classifier, or {@link #setUp(jsat.classifiers.CategoricalData[], int,
* jsat.classifiers.CategoricalData) } to prepare for online updates. Once one
* of these is called, it should then be safe to call
* {@link #update(jsat.classifiers.DataPoint, int) } without getting a
* {@link UntrainedModelException}. Some online learners may require one of the
* train methods to be called first.
*
* @author Edward Raff
*/
public interface UpdateableClassifier extends Classifier
{
/**
* Prepares the classifier to begin learning from its
* {@link #update(jsat.classifiers.DataPoint, int) } method.
*
* @param categoricalAttributes an array containing the categorical
* attributes that will be in each data point
* @param numericAttributes the number of numeric attributes that will be in
* each data point
* @param predicting the information for the target class that will be
* predicted
*/
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting);
/**
* Updates the classifier by giving it a new data point to learn from.
* @param dataPoint the data point to learn
* @param weight weight of the given data point being added
* @param targetClass the target class of the data point
*/
public void update(DataPoint dataPoint, double weight, int targetClass);
/**
* Updates the classifier by giving it a new data point to learn from.
* @param dataPoint the data point to learn
* @param targetClass the target class of the data point
*/
default public void update(DataPoint dataPoint, int targetClass)
{
update(dataPoint, 1.0, targetClass);
}
@Override
public UpdateableClassifier clone();
}
| 2,604 | 41.016129 | 114 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/WarmClassifier.java | package jsat.classifiers;
/**
* This interface is meant for models that support efficient warm starting from
* the solution of a previous model. Training with a warm start means that
* instead of solving the problem from scratch, the code can use a previous
* solution to start closer towards its goal. <br>
* <br>
* Some algorithm may be able to warm start from solutions of the same form,
* even if they were trained by a different algorithm. Other algorithms may only
* be able to warm start from the same algorithm. There may also be restrictions
* that the warm start can only be from a solution trained on the exact same
* data set. The latter case is indicated by the {@link #warmFromSameDataOnly()}
* method. <br>
* <br>
* Just because a classifier fits the type that the warm start interface states
* doesn't mean that it is a valid classifier to warm start from. <i>Classifiers
* of the same class trained on the same data must <b>always</b> be valid to
* warm start from. </i>
* <br>
* <br>
* Note: The use of this class is still under development, and may change in the
* future.
*
* @author Edward Raff
*/
public interface WarmClassifier extends Classifier
{
/**
* Some models can only be warm started from a solution trained on the
* exact same data set as the model it is warm starting from. If this is the
* case {@code true} will be returned. The behavior for training on a
* different data set when this is defined is undefined. It may cause an
* error, or it may cause the algorithm to take longer or reach a worse
* solution. <br>
* When {@code true}, it is important that the data set be unaltered - this
* includes mutating the values stored or re-arranging the data points
* within the data set.
*
* @return {@code true} if the algorithm can only be warm started from the
* model trained on the exact same data set.
*/
public boolean warmFromSameDataOnly();
/**
* Trains the classifier and constructs a model for classification using the
* given data set. If the training method knows how, it will used the
* <tt>threadPool</tt> to conduct training in parallel. This method will
* block until the training has completed.
*
* @param dataSet the data set to train on
* @param warmSolution the solution to use to warm start this model
* @param parallel {@code true} if the training should be done using
* multiple-cores, {@code false} for single threaded.
*/
public void train(ClassificationDataSet dataSet, Classifier warmSolution, boolean parallel);
/**
* Trains the classifier and constructs a model for classification using the
* given data set.
*
* @param dataSet the data set to train on
* @param warmSolution the solution to use to warm start this model
*/
default public void train(ClassificationDataSet dataSet, Classifier warmSolution)
{
train(dataSet, warmSolution, false);
}
}
| 3,054 | 42.642857 | 96 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/AODE.java | package jsat.classifiers.bayesian;
import jsat.classifiers.*;
import jsat.exceptions.FailedToFitException;
import jsat.utils.concurrent.ParallelUtils;
/**
* Averaged One-Dependence Estimators (AODE) is an extension of Naive Bayes that
* attempts to be more accurate by reducing the independence assumption. For
* <i>n</i> data points with <i>d</i> categorical features, <i>d</i>
* {@link ODE} classifier are created, each with a dependence on a different
* attribute. The results of these classifiers is averaged to produce a final
* result. The construction time is <i>O(n d<sup>2</sup>)</i>. Because of this
* extra dependence requirement, the implementation only allows for categorical
* features. <br>
* <br>
* See: Webb, G., & Boughton, J. (2005). <i>Not so naive bayes: Aggregating
* one-dependence estimators</i>. Machine Learning, 1–24. Retrieved from
* <a href="http://www.springerlink.com/index/U8W306673M1P866K.pdf">here</a>
*
* @author Edward Raff
*/
public class AODE extends BaseUpdateableClassifier
{
private static final long serialVersionUID = 8386506277969540732L;
protected CategoricalData predicting;
protected ODE[] odes;
/**
* The minimum value to use a probability
*/
private double m = 20;
/**
* Creates a new AODE classifier.
*/
public AODE()
{
}
/**
* Creates a copy of an AODE classifier
* @param toClone the classifier to clone
*/
protected AODE(AODE toClone)
{
if(toClone.odes != null)
{
this.odes = new ODE[toClone.odes.length];
for(int i = 0; i < this.odes.length; i++)
this.odes[i] = toClone.odes[i].clone();
this.predicting = toClone.predicting.clone();
}
this.m = toClone.m;
}
@Override
public AODE clone()
{
return new AODE(this);
}
@Override
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting)
{
if(categoricalAttributes.length < 1)
throw new FailedToFitException("At least 2 categorical varaibles are needed for AODE");
this.predicting = predicting;
odes = new ODE[categoricalAttributes.length];
for(int i = 0; i < odes.length; i++)
{
odes[i] = new ODE(i);
odes[i].setUp(categoricalAttributes, numericAttributes, predicting);
}
}
@Override
public void train(final ClassificationDataSet dataSet, boolean parallel)
{
setUp(dataSet.getCategories(), dataSet.getNumNumericalVars(),
dataSet.getPredicting());
ParallelUtils.range(odes.length, parallel).forEach(z->
{
ODE ode = odes[z];
for (int i = 0; i < dataSet.size(); i++)
ode.update(dataSet.getDataPoint(i), dataSet.getWeight(i), dataSet.getDataPointCategory(i));
});
}
@Override
public void update(DataPoint dataPoint, double weight, int targetClass)
{
for(ODE ode : odes)
ode.update(dataPoint, targetClass);
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());
int[] catVals = data.getCategoricalValues();
for(int c = 0; c < cr.size(); c++)
{
double prob = 0.0;
for (ODE ode : odes)
if (ode.priors[c][catVals[ode.dependent]] < m)
continue;
else
prob += Math.exp(ode.getLogPrb(catVals, c));
cr.setProb(c, prob);
}
cr.normalize();
return cr;
}
@Override
public boolean supportsWeightedData()
{
return true;
}
/**
* Sets the minimum prior observation value needed for an attribute
* combination to have enough support to be included in the final estimate.
*
* @param m the minimum needed score
*/
public void setM(double m)
{
if(m < 0 || Double.isInfinite(m) || Double.isNaN(m))
throw new ArithmeticException("The minimum count must be a non negative number");
this.m = m;
}
/**
* Returns the minimum needed score
* @return the minimum needed score
*/
public double getM()
{
return m;
}
}
| 4,473 | 28.434211 | 113 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/BestClassDistribution.java |
package jsat.classifiers.bayesian;
import java.util.*;
import java.util.stream.Collectors;
import jsat.classifiers.*;
import jsat.distributions.multivariate.MultivariateDistribution;
import jsat.parameters.*;
import jsat.utils.concurrent.ParallelUtils;
/**
* BestClassDistribution is a generic class for performing classification by fitting a {@link MultivariateDistribution} to each class. The distribution
* is supplied by the user, and each class if fit to the same type of distribution. Classification is then performed by returning
* the class of the most likely distribution given the data point.
*
* @author Edward Raff
*/
public class BestClassDistribution implements Classifier, Parameterized
{
private static final long serialVersionUID = -1746145372146154228L;
private MultivariateDistribution baseDist;
private List<MultivariateDistribution> dists;
/**
* The prior probabilities of each class
*/
private double priors[];
/**
* Controls whether or no the prior probability will be used when computing probabilities
*/
private boolean usePriors;
/**
* The default value for whether or not to use the prior probability of a
* class when making classification decisions is {@value #USE_PRIORS}.
*/
public static final boolean USE_PRIORS = true;
public BestClassDistribution(MultivariateDistribution baseDist)
{
this(baseDist, USE_PRIORS);
}
public BestClassDistribution(MultivariateDistribution baseDist, boolean usePriors)
{
this.baseDist = baseDist;
this.usePriors = usePriors;
}
/**
* Copy constructor
* @param toCopy the object to copy
*/
public BestClassDistribution(BestClassDistribution toCopy)
{
if(toCopy.priors != null)
this.priors = Arrays.copyOf(toCopy.priors, toCopy.priors.length);
this.baseDist = toCopy.baseDist.clone();
if(toCopy.dists != null)
{
this.dists = new ArrayList<>(toCopy.dists.size());
for(MultivariateDistribution md : toCopy.dists)
this.dists.add(md == null? null : md.clone());
}
}
/**
* Controls whether or not the priors will be used for classification. This value can be
* changed at any time, before or after training has occurred.
*
* @param usePriors <tt>true</tt> to use the prior probabilities for each class, <tt>false</tt> to ignore them.
*/
public void setUsePriors(boolean usePriors)
{
this.usePriors = usePriors;
}
/**
* Returns whether or not this object uses the prior probabilities for classification.
* @return {@code true} if the prior probabilities are being used,
* {@code false} if not.
*/
public boolean isUsePriors()
{
return usePriors;
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(dists.size());
for(int i = 0; i < dists.size(); i++)
{
if(dists.get(i) == null)
continue;
double p = 0 ;
try
{
p = dists.get(i).pdf(data.getNumericalValues());
}
catch(ArithmeticException ex)
{
}
if(usePriors)
p *= priors[i];
cr.setProb(i, p);
}
cr.normalize();
return cr;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
priors = dataSet.getPriors();
dists = ParallelUtils.range(dataSet.getClassSize(), parallel).mapToObj((int i) ->
{
MultivariateDistribution dist = baseDist.clone();
List<DataPoint> samp = dataSet.getSamples(i);
if(samp.isEmpty())
{
return (MultivariateDistribution) null;
}
dist.setUsingDataList(samp);
return dist;
}).collect(Collectors.toList());
}
@Override
public boolean supportsWeightedData()
{
return false;
}
@Override
public BestClassDistribution clone()
{
return new BestClassDistribution(this);
}
}
| 4,330 | 28.664384 | 152 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/ConditionalProbabilityTable.java |
package jsat.classifiers.bayesian;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import jsat.DataSet;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.CategoricalResults;
import jsat.classifiers.ClassificationDataSet;
import jsat.classifiers.Classifier;
import jsat.classifiers.DataPoint;
import jsat.classifiers.DataPointPair;
import jsat.exceptions.FailedToFitException;
import jsat.exceptions.UntrainedModelException;
import jsat.utils.IntSet;
/**
* The conditional probability table (CPT) is a classifier for categorical attributes. It builds the whole
* conditional probability table for a data set. The size of the CPT grows exponentially with the number of dimensions and options,
* and requires exponentially more data to get a good fit. CPTs can be useful for small data sets, or as a building
* block for another algorithm
*
* @author Edward Raff
*/
public class ConditionalProbabilityTable implements Classifier
{
private static final long serialVersionUID = -287709075031023626L;
/**
* The predicting target class
*/
private CategoricalData predicting;
/**
* The flat array that stores the n dimensional table
*/
private double[] countArray;
/**
* Set subset of the variables we will be using
*/
private Map<Integer, CategoricalData> valid;
/**
* Maps the index order for the CPT to the index values from the training data set
*/
private int[] realIndexToCatIndex;
/**
* Maps the index values of the training set to the index values used by the CPT.
* A value of '-1' indicates that the feature is not in the CPT
*/
private int[] catIndexToRealIndex;
/**
* the dimension size for each category, ie: the number of options for each category
*/
private int[] dimSize;
/**
* The index of the predicting attribute, which is the number of categorical features in the training data set.
*/
private int predictingIndex;
public CategoricalResults classify(DataPoint data)
{
if(catIndexToRealIndex[predictingIndex] < 0)
throw new UntrainedModelException("CPT has not been trained for a classification problem");
CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());
int[] cord = new int[dimSize.length];
dataPointToCord(new DataPointPair<Integer>(data, -1), predictingIndex, cord);
for(int i = 0; i < cr.size(); i++)
{
cord[catIndexToRealIndex[predictingIndex]] = i;
cr.setProb(i, countArray[cordToIndex(cord)]);
}
cr.normalize();//Turn counts into probabilityes
return cr;
}
/**
* Returns the number of dimensions in the CPT
* @return the number of dimensions in the CPT
*/
public int getDimensionSize()
{
return dimSize.length;
}
/**
* Converts a data point pair into a coordinate. The paired value contains the value for the predicting index.
* Though this value will not be used if the predicting class of the original data set was not used to make the table.
*
* @param dataPoint the DataPointPair to convert
* @param targetClass the index in the original data set of the category that we would like to predict
* @param cord the array to store the coordinate in.
* @return the value of the target class for the given data point
* @throws ArithmeticException if the <tt>cord</tt> array does not match the {@link #getDimensionSize() dimension} of the CPT
*/
public int dataPointToCord(DataPointPair<Integer> dataPoint, int targetClass, int[] cord)
{
if(cord.length != getDimensionSize())
throw new ArithmeticException("Storage space and CPT dimension miss match");
DataPoint dp = dataPoint.getDataPoint();
int skipVal = -1;
//Set up cord
for(int i = 0; i < dimSize.length; i++)
{
if(realIndexToCatIndex[i] == targetClass)
{
if(targetClass == dp.numCategoricalValues())
skipVal = dataPoint.getPair();
else
skipVal = dp.getCategoricalValue(realIndexToCatIndex[i]);
}
if(realIndexToCatIndex[i] == predictingIndex)
cord[i] = dataPoint.getPair();
else
cord[i] = dp.getCategoricalValue(realIndexToCatIndex[i]);
}
return skipVal;
}
public void train(ClassificationDataSet dataSet, boolean parallel)
{
train(dataSet);
}
public void train(ClassificationDataSet dataSet)
{
Set<Integer> all = new IntSet();
for(int i = 0; i < dataSet.getNumCategoricalVars()+1; i++)
all.add(i);
trainC(dataSet, all);
}
/**
* Creates a CPT using only a subset of the features specified by <tt>categoriesToUse</tt>.
*
* @param dataSet the data set to train from
* @param categoriesToUse the attributes to use in training. Each value corresponds to the categorical
* index in <tt>dataSet</tt>, and adding the value {@link DataSet#getNumCategoricalVars() }, which is
* not a valid index, indicates to used the {@link ClassificationDataSet#getPredicting() predicting class}
* of the data set in the CPT.
*/
public void trainC(ClassificationDataSet dataSet, Set<Integer> categoriesToUse)
{
if(categoriesToUse.size() > dataSet.getNumFeatures()+1)
throw new FailedToFitException("CPT can not train on a number of features greater then the dataset's feature count. "
+ "Specified " + categoriesToUse.size() + " but data set has only " + dataSet.getNumFeatures());
CategoricalData[] tmp = dataSet.getCategories();
predicting = dataSet.getPredicting();
predictingIndex = dataSet.getNumCategoricalVars();
valid = new HashMap<Integer, CategoricalData>();
realIndexToCatIndex = new int[categoriesToUse.size()];
catIndexToRealIndex = new int[dataSet.getNumCategoricalVars()+1];//+1 for the predicting
Arrays.fill(catIndexToRealIndex, -1);//-1s are non existant values
dimSize = new int[realIndexToCatIndex.length];
int flatSize = 1;//The number of bins in the n dimensional array
int k = 0;
for(int i : categoriesToUse)
{
if(i == predictingIndex)//The predicint class is treated seperatly
continue;
CategoricalData dataInfo = tmp[i];
flatSize *= dataInfo.getNumOfCategories();
valid.put(i, dataInfo);
realIndexToCatIndex[k] = i;
catIndexToRealIndex[i] = k;
dimSize[k++] = dataInfo.getNumOfCategories();
}
if(categoriesToUse.contains(predictingIndex))
{
//Lastly the predicing quantity
flatSize *= predicting.getNumOfCategories();
realIndexToCatIndex[k] = predictingIndex;
catIndexToRealIndex[predictingIndex] = k;
dimSize[k] = predicting.getNumOfCategories();
valid.put(predictingIndex, predicting);
}
countArray = new double[flatSize];
Arrays.fill(countArray, 1);//Laplace correction
int[] cordinate = new int[dimSize.length];
for(int i = 0; i < dataSet.size(); i++)
{
DataPoint dp = dataSet.getDataPoint(i);
for (int j = 0; j < realIndexToCatIndex.length; j++)
if (realIndexToCatIndex[j] != predictingIndex)
cordinate[j] = dp.getCategoricalValue(realIndexToCatIndex[j]);
else
cordinate[j] = dataSet.getDataPointCategory(i);
countArray[cordToIndex(cordinate)]+= dataSet.getWeight(i);
}
}
/**
* Queries the CPT for the probability that the class value of <tt>targetClas</tt> would occur with the given DataPointPair.
* @param targetClass the index in the original data set of the class that we want the probability of
* @param dataPoint the data point of values paired with the value of the predicting attribute in the original training set
* @return the probability in [0,1] of the target class value occurring with the given DataPointPair
*/
public double query(int targetClass, DataPointPair<Integer> dataPoint)
{
int[] cord = new int[dimSize.length];
int skipVal = dataPointToCord(dataPoint, targetClass, cord);
return query(targetClass, skipVal, cord);
}
/**
* Queries the CPT for the probability of the target class occurring with the specified value given the class values of the other attributes
*
* @param targetClass the index in the original data set of the class that we want to probability of
* @param targetValue the value of the <tt>targetClass</tt> that we want to probability of occurring
* @param cord the coordinate array that corresponds the the class values for the CPT, where the coordinate of the <tt>targetClass</tt> may contain any value.
* @return the probability in [0, 1] of the <tt>targetClass</tt> occurring with the <tt>targetValue</tt> given the information in <tt>cord</tt>
* @see #dataPointToCord(jsat.classifiers.DataPointPair, int, int[])
*/
public double query(int targetClass, int targetValue, int[] cord)
{
double sumVal = 0;
double targetVal = 0;
int realTargetIndex = catIndexToRealIndex[targetClass];
CategoricalData queryData = valid.get(targetClass);
//Now do all other target class posibilty querys
for (int i = 0; i < queryData.getNumOfCategories(); i++)
{
cord[realTargetIndex] = i;
double tmp = countArray[cordToIndex(cord)];
sumVal += tmp;
if (i == targetValue)
targetVal = tmp;
}
return targetVal/sumVal;
}
/**
* Computes the index into the {@link #countArray} using the given coordinate
* @param cords the coordinate value in question
* @return the index for the given coordinate
*/
private int cordToIndex(int... cords)
{
if(cords.length != realIndexToCatIndex.length)
throw new RuntimeException("Something bad");
int index = 0;
for(int i = 0; i < cords.length; i++)
{
index = cords[i] + dimSize[i]*index;
}
return index;
}
/**
* Computes the index into the {@link #countArray} using the given data point
* @param dataPoint the data point to get the index of
* @return the index for the given data point
*/
@SuppressWarnings("unused")
private int cordToIndex(DataPointPair<Integer> dataPoint)
{
DataPoint dp = dataPoint.getDataPoint();
int index = 0;
for(int i = 0; i < dimSize.length; i++)
index = dp.getCategoricalValue(realIndexToCatIndex[i]) + dimSize[i]*index;
return index;
}
public boolean supportsWeightedData()
{
return true;
}
@Override
public Classifier clone()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 11,522 | 38.193878 | 163 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/MultinomialNaiveBayes.java |
package jsat.classifiers.bayesian;
import static java.lang.Math.exp;
import java.util.Arrays;
import jsat.classifiers.*;
import jsat.exceptions.FailedToFitException;
import jsat.exceptions.UntrainedModelException;
import jsat.linear.IndexValue;
import jsat.linear.Vec;
import jsat.math.MathTricks;
import jsat.parameters.Parameterized;
/**
* An implementation of the Multinomial Naive Bayes model (MNB). In this model,
* vectors are implicitly assumed to be sparse and that zero values can be
* skipped. This model requires that all numeric features be non negative, any
* negative value will be treated as a zero. <br>
* <br>Note: the is no reason to ever use more than one
* {@link #setEpochs(int) epoch} for MNB<br>
* <br>MNB requires taking the log probabilities to perform predictions, which
* created a trade off. Updating the classifier requires the non log form, but
* updates require the log form, making classification take considerably longer
* to take the logs of the probabilities. This can be reduced by
* {@link #finalizeModel() finalizing} the model. This prevents the model from
* being updated further, but reduces classification time. By default, this will
* be done after a call to
* {@link #train(jsat.classifiers.ClassificationDataSet) } but not after
* {@link #update(jsat.classifiers.DataPoint, int) }
*
* @author Edward Raff
*/
public class MultinomialNaiveBayes extends BaseUpdateableClassifier implements Parameterized
{
private static final long serialVersionUID = -469977945722725478L;
private double[][][] apriori;
private double[][] wordCounts;
private double[] totalWords;
private double priorSum = 0;
private double[] priors;
/**
* Smoothing correction.
* Added in classification instead of addition
*/
private double smoothing;
private boolean finalizeAfterTraining = true;
/**
* No more training
*/
private boolean finalized;
/**
* Creates a new Multinomial model with laplace smoothing
*/
public MultinomialNaiveBayes()
{
this(1.0);
}
/**
* Creates a new Multinomial model with the given amount of smoothing
* @param smoothing the amount of smoothing to apply
*/
public MultinomialNaiveBayes(double smoothing)
{
setSmoothing(smoothing);
setEpochs(1);
}
/**
* Copy constructor
* @param other the one to copy
*/
protected MultinomialNaiveBayes(MultinomialNaiveBayes other)
{
this(other.smoothing);
if(other.apriori != null)
{
this.apriori = new double[other.apriori.length][][];
this.wordCounts = new double[other.wordCounts.length][];
this.totalWords = Arrays.copyOf(other.totalWords, other.totalWords.length);
this.priors = Arrays.copyOf(other.priors, other.priors.length);
this.priorSum = other.priorSum;
for(int c = 0; c < other.apriori.length; c++)
{
this.apriori[c] = new double[other.apriori[c].length][];
for(int j = 0; j < other.apriori[c].length; j++)
this.apriori[c][j] = Arrays.copyOf(other.apriori[c][j],
other.apriori[c][j].length);
this.wordCounts[c] = Arrays.copyOf(other.wordCounts[c], other.wordCounts[c].length);
}
this.priorSum = other.priorSum;
this.priors = Arrays.copyOf(other.priors, other.priors.length);
}
this.finalizeAfterTraining = other.finalizeAfterTraining;
this.finalized = other.finalized;
}
/**
* Sets the amount of smoothing applied to the model. <br>
* Using a value of 1.0 is equivalent to laplace smoothing
* <br><br>
* The smoothing can be changed after the model has already been trained
* without needed to re-train the model for the change to take effect.
*
* @param smoothing the positive smoothing constant
*/
public void setSmoothing(double smoothing)
{
if(Double.isNaN(smoothing) || Double.isInfinite(smoothing) || smoothing <= 0)
throw new IllegalArgumentException("Smoothing constant must be in range (0,Inf), not " + smoothing);
this.smoothing = smoothing;
}
/**
*
* @return the smoothing applied to categorical counts
*/
public double getSmoothing()
{
return smoothing;
}
/**
* If set {@code true}, the model will be finalized after a call to
* {@link #train(jsat.classifiers.ClassificationDataSet) }. This prevents
* the model from being updated in an online fashion for an reduction in
* classification time.
*
* @param finalizeAfterTraining {@code true} to finalize after a call to
* train, {@code false} to keep the model updatable.
*/
public void setFinalizeAfterTraining(boolean finalizeAfterTraining)
{
this.finalizeAfterTraining = finalizeAfterTraining;
}
/**
* Returns {@code true} if the model will be finalized after batch training.
* {@code false} if it will be left in an updatable state.
* @return {@code true} if the model will be finalized after batch training.
*/
public boolean isFinalizeAfterTraining()
{
return finalizeAfterTraining;
}
@Override
public MultinomialNaiveBayes clone()
{
return new MultinomialNaiveBayes(this);
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
super.train(dataSet, parallel);
if(finalizeAfterTraining)
finalizeModel();
}
@Override
public void train(ClassificationDataSet dataSet)
{
super.train(dataSet);
if(finalizeAfterTraining)
finalizeModel();
}
/**
* Finalizes the current model. This prevents the model from being updated
* further, causing {@link #update(jsat.classifiers.DataPoint, int) } to
* throw an exception. This finalization reduces the cost of calling
* {@link #classify(jsat.classifiers.DataPoint) }
*/
public void finalizeModel()
{
if(finalized)
return;
final double priorSumSmooth = priorSum + priors.length * smoothing;
for (int c = 0; c < priors.length; c++)
{
double logProb = Math.log((priors[c] + smoothing) / priorSumSmooth);
priors[c] = logProb;
double[] counts = wordCounts[c];
double logTotalCounts = Math.log(totalWords[c] + smoothing * counts.length);
for(int i = 0; i < counts.length; i++)
{
//(n/N)^obv
counts[i] = Math.log(counts[i] + smoothing) - logTotalCounts;
}
for (int j = 0; j < apriori[c].length; j++)
{
double sum = 0;
for (int z = 0; z < apriori[c][j].length; z++)
sum += apriori[c][j][z] + smoothing;
for (int z = 0; z < apriori[c][j].length; z++)
apriori[c][j][z] = Math.log( (apriori[c][j][z]+smoothing)/sum);
}
}
finalized = true;
}
@Override
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting)
{
final int nCat = predicting.getNumOfCategories();
apriori = new double[nCat][categoricalAttributes.length][];
wordCounts = new double[nCat][numericAttributes];
totalWords = new double[nCat];
priors = new double[nCat];
priorSum = 0.0;
for (int i = 0; i < nCat; i++)
for (int j = 0; j < categoricalAttributes.length; j++)
apriori[i][j] = new double[categoricalAttributes[j].getNumOfCategories()];
finalized = false;
}
@Override
public void update(DataPoint dataPoint, double weight, int targetClass)
{
if(finalized)
throw new FailedToFitException("Model has already been finalized, and can no longer be updated");
final Vec x = dataPoint.getNumericalValues();
//Categorical value updates
int[] catValues = dataPoint.getCategoricalValues();
for(int j = 0; j < apriori[targetClass].length; j++)
apriori[targetClass][j][catValues[j]]+=weight;
double localCountsAdded = 0;
for(IndexValue iv : x)
{
final double v = iv.getValue();
if(v < 0)
continue;
wordCounts[targetClass][iv.getIndex()] += v*weight;
localCountsAdded += v*weight;
}
totalWords[targetClass] += localCountsAdded;
priors[targetClass] += weight;
priorSum += weight;
}
@Override
public CategoricalResults classify(DataPoint data)
{
if(apriori == null)
throw new UntrainedModelException("Model has not been intialized");
CategoricalResults results = new CategoricalResults(apriori.length);
double[] logProbs = new double[apriori.length];
double maxLogProg = Double.NEGATIVE_INFINITY;
Vec numVals = data.getNumericalValues();
if(finalized)
{
for(int c = 0; c < priors.length; c++)
{
double logProb = priors[c];
double[] counts = wordCounts[c];
for (IndexValue iv : numVals)
{
//(n/N)^obv
logProb += iv.getValue() * counts[iv.getIndex()];
}
for (int j = 0; j < apriori[c].length; j++)
{
logProb += apriori[c][j][data.getCategoricalValue(j)];
}
logProbs[c] = logProb;
maxLogProg = Math.max(maxLogProg, logProb);
}
}
else
{
final double priorSumSmooth = priorSum+logProbs.length*smoothing;
for(int c = 0; c < priors.length; c++)
{
double logProb = Math.log((priors[c]+smoothing)/priorSumSmooth);
double[] counts = wordCounts[c];
double logTotalCounts = Math.log(totalWords[c]+smoothing*counts.length);
for (IndexValue iv : numVals)
{
//(n/N)^obv
logProb += iv.getValue() * (Math.log(counts[iv.getIndex()]+smoothing) - logTotalCounts);
}
for (int j = 0; j < apriori[c].length; j++)
{
double sum = 0;
for (int z = 0; z < apriori[c][j].length; z++)
sum += apriori[c][j][z]+smoothing;
double p = apriori[c][j][data.getCategoricalValue(j)]+smoothing;
logProb += Math.log(p / sum);
}
logProbs[c] = logProb;
maxLogProg = Math.max(maxLogProg, logProb);
}
}
double denom = MathTricks.logSumExp(logProbs, maxLogProg);
for (int i = 0; i < results.size(); i++)
results.setProb(i, exp(logProbs[i] - denom));
results.normalize();
return results;
}
@Override
public boolean supportsWeightedData()
{
return true;
}
}
| 11,424 | 33.412651 | 113 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/MultivariateNormals.java | package jsat.classifiers.bayesian;
import jsat.distributions.multivariate.NormalM;
/**
* This classifier can be seen as an extension of {@link NaiveBayes}. Instead of treating the variables as independent,
* each class uses all of its variables to fit a {@link NormalM Multivariate Normal} distribution. As such, it can only
* handle numerical attributes. However, if the classes are normally distributed, it will produce optimal classification
* results. The less normal the true distributions are, the less accurate the classifier will be.
*
* @author Edward Raff
*/
public class MultivariateNormals extends BestClassDistribution
{
private static final long serialVersionUID = 5977979334930517655L;
public MultivariateNormals(boolean usePriors)
{
super(new NormalM(), usePriors);
}
/**
* Creates a new class for classification by feating each class to a {@link NormalM Multivariate Normal Distribution}.
*/
public MultivariateNormals()
{
super(new NormalM());
}
/**
* Copy constructor
* @param toCopy the object to copy
*/
public MultivariateNormals(MultivariateNormals toCopy)
{
super(toCopy);
}
@Override
public boolean supportsWeightedData()
{
return true;
}
@Override
public MultivariateNormals clone()
{
return new MultivariateNormals(this);
}
}
| 1,424 | 25.388889 | 123 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/NaiveBayes.java |
package jsat.classifiers.bayesian;
import static java.lang.Math.exp;
import static java.lang.Math.log;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import jsat.classifiers.*;
import static jsat.distributions.DistributionSearch.getBestDistribution;
import jsat.distributions.*;
import jsat.distributions.empirical.KernelDensityEstimator;
import jsat.linear.*;
import jsat.math.MathTricks;
import jsat.parameters.*;
import jsat.utils.DoubleList;
import jsat.utils.concurrent.ParallelUtils;
/**
*
* Provides an implementation of the Naive Bayes classifier that assumes numeric
* features come from some continuous probability distribution. By default this
* implementation restricts itself to only the {@link Normal Gaussian}
* distribution, and becomes Gaussian Naive Bayes. Other distributions are
* supported, and a {@link KernelDensityEstimator} can be used as well.
* <br><br>
* By default, this implementation assumes that the input vectors are sparse
* and the distribution will only be estimated by the non-zero values, and
* features that are zero will be ignored during prediction time. This should be
* turned off when using dense data by calling {@link #setSparceInput(boolean) }
* <br><br>
* Naive Bayes assumes that all attributes are perfectly independent.
*
* @author Edward Raff
*/
public class NaiveBayes implements Classifier, Parameterized
{
private static final long serialVersionUID = -2437775653277531182L;
/**
*
*/
private double[][][] apriori;
private ContinuousDistribution[][] distributions;
private NumericalHandeling numericalHandling;
private double[] priors;
/**
* Handles how vectors are handled. If true, it is assumed vectors are sparce - and zero values will be ignored when training and classifying.
*/
private boolean sparceInput = true;
/**
* The default method of handling numeric attributes is {@link NumericalHandeling#NORMAL}.
*/
public static final NumericalHandeling defaultHandling = NumericalHandeling.NORMAL;
/**
* There are multiple ways of handling numerical attributes. These provide the
* different ways that NaiveBayes can deal with them.
*/
public enum NumericalHandeling
{
/**
* All numerical attributes are fit to a {@link Normal} distribution.
*//**
* All numerical attributes are fit to a {@link Normal} distribution.
*/
NORMAL
{
@Override
protected ContinuousDistribution fit(Vec v)
{
return getBestDistribution(v, new Normal(0, 1));
}
},
/**
* The best fitting {@link ContinuousDistribution} is selected by
* {@link DistributionSearch#getBestDistribution(jsat.linear.Vec) }
*/
BEST_FIT
{
@Override
protected ContinuousDistribution fit(Vec v)
{
return getBestDistribution(v);
}
},
/**
* The best fitting {@link ContinuousDistribution} is selected by
* {@link DistributionSearch#getBestDistribution(jsat.linear.Vec, double) },
* and provides a cut off value to use the {@link KernelDensityEstimator} instead
*/
BEST_FIT_KDE
{
private double cutOff = 0.9;
//XXX these methods are never and cannot be used
// /**
// * Sets the cut off value used before fitting an empirical distribution
// * @param c the cut off value, should be between (0, 1).
// */
// public void setCutOff(double c)
// {
// cutOff = c;
// }
//
// /**
// * Returns the cut off value used before fitting an empirical distribution
// * @return the cut off value used before fitting an empirical distribution
// */
// public double getCutOff()
// {
// return cutOff;
// }
@Override
protected ContinuousDistribution fit(Vec v)
{
return getBestDistribution(v, cutOff);
}
};
abstract protected ContinuousDistribution fit(Vec y);
}
/**
* Creates a new Naive Bayes classifier that uses the specific method for
* handling numeric features.
* @param numericalHandling the method to use for numeric features
*/
public NaiveBayes(NumericalHandeling numericalHandling)
{
this.numericalHandling = numericalHandling;
}
/**
* Creates a new Gaussian Naive Bayes classifier
*/
public NaiveBayes()
{
this(defaultHandling);
}
/**
* Sets the method used by this instance for handling numerical attributes.
* This has no effect on an already trained classifier, but will change the result if trained again.
*
* @param numericalHandling the method to use for numerical attributes
*/
public void setNumericalHandling(NumericalHandeling numericalHandling)
{
this.numericalHandling = numericalHandling;
}
/**
* Returns the method used to handle numerical attributes
* @return the method used to handle numerical attributes
*/
public NumericalHandeling getNumericalHandling()
{
return numericalHandling;
}
/**
* Returns <tt>true</tt> if the Classifier assumes that data points are sparce.
* @return <tt>true</tt> if the Classifier assumes that data points are sparce.
* @see #setSparceInput(boolean)
*/
public boolean isSparceInput()
{
return sparceInput;
}
/**
* Tells the Naive Bayes classifier to
* assume the importance of sparseness
* in the numerical values. This means
* that values of zero will be ignored
* in computation and classification.<br>
* This allows faster, more efficient
* computation of results if the data
* points are indeed sparce. This will
* also produce different results.
* This value should not be changed
* after training and before classification.
*
* @param sparceInput <tt>true</tt> to assume sparseness in the data, <tt>false</tt> to ignore it and assume zeros are meaningful values.
* @see #isSparceInput()
*/
public void setSparceInput(boolean sparceInput)
{
this.sparceInput = sparceInput;
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults results = new CategoricalResults(distributions.length);
double[] logProbs = new double[distributions.length];
Vec numVals = data.getNumericalValues();
double maxLogProg = Double.NEGATIVE_INFINITY;
for( int i = 0; i < distributions.length; i++)
{
double logProb = 0;
if(sparceInput)
{
Iterator<IndexValue> iter = numVals.getNonZeroIterator();
while(iter.hasNext())
{
IndexValue indexValue = iter.next();
int j = indexValue.getIndex();
double logPDF;
if(distributions[i][j] == null)
logPDF = Double.NEGATIVE_INFINITY;//Should not occur
else
logPDF = distributions[i][j].logPdf(indexValue.getValue());
if(Double.isInfinite(logPDF))//Avoid propigation -infinty when the probability is zero
logProb += log(1e-16);//
else
logProb += logPDF;
}
}
else
{
for(int j = 0; j < distributions[i].length; j++)
{
double logPDF;
if(distributions[i][j] == null)
logPDF = Double.NEGATIVE_INFINITY;//Should not occur
else
logPDF = distributions[i][j].logPdf(numVals.get(j));
if(Double.isInfinite(logPDF))//Avoid propigation -infinty when the probability is zero
logProb += log(1e-16);//
else
logProb += logPDF;
}
}
//the i goes up to the number of categories, same for aprioror
for(int j = 0; j < apriori[i].length; j++)
{
double p = apriori[i][j][data.getCategoricalValue(j)];
logProb += log(p);
}
logProb += log(priors[i]);
logProbs[i] = logProb;
maxLogProg = Math.max(maxLogProg, logProb);
}
if(maxLogProg == Double.NEGATIVE_INFINITY)//Everything reported no!
{
for(int i = 0; i < results.size(); i++)
results.setProb(i, 1.0/results.size());
return results;
}
double denom = MathTricks.logSumExp(logProbs, maxLogProg);
for(int i = 0; i < results.size(); i++)
results.setProb(i, exp(logProbs[i]-denom));
results.normalize();
return results;
}
@Override
public NaiveBayes clone()
{
NaiveBayes newBayes = new NaiveBayes(numericalHandling);
if(this.apriori != null)
{
newBayes.apriori = new double[this.apriori.length][][];
for(int i = 0; i < this.apriori.length; i++)
{
newBayes.apriori[i] = new double[this.apriori[i].length][];
for(int j = 0; this.apriori[i].length > 0 && j < this.apriori[i][j].length; j++)
newBayes.apriori[i][j] = Arrays.copyOf(this.apriori[i][j], this.apriori[i][j].length);
}
}
if(this.distributions != null)
{
newBayes.distributions = new ContinuousDistribution[this.distributions.length][];
for(int i = 0; i < this.distributions.length; i++)
{
newBayes.distributions[i] = new ContinuousDistribution[this.distributions[i].length];
for(int j = 0; j < this.distributions[i].length; j++)
newBayes.distributions[i][j] = this.distributions[i][j].clone();
}
}
if(this.priors != null)
newBayes.priors = Arrays.copyOf(priors, priors.length);
return newBayes;
}
@Override
public boolean supportsWeightedData()
{
return false;
}
/**
* Runnable task for selecting the right distribution for each task
*/
private class DistributionSelectRunable implements Runnable
{
int i;
int j;
Vec v;
CountDownLatch countDown;
public DistributionSelectRunable(int i, int j, Vec v, CountDownLatch countDown)
{
this.i = i;
this.j = j;
this.v = v;
this.countDown = countDown;
}
public void run()
{
try
{
distributions[i][j] = numericalHandling.fit(v);
}
catch (ArithmeticException e)
{
distributions[i][j] = null;
}
countDown.countDown();
}
}
private class AprioriCounterRunable implements Runnable
{
int i;
int j;
List<DataPoint> dataSamples;
CountDownLatch latch;
public AprioriCounterRunable(int i, int j, List<DataPoint> dataSamples, CountDownLatch latch)
{
this.i = i;
this.j = j;
this.dataSamples = dataSamples;
this.latch = latch;
}
@Override
public void run()
{
for (DataPoint point : dataSamples)//Count each occurance
{
apriori[i][j][point.getCategoricalValue(j)]++;
}
//Convert the coutns to apriori probablities by dividing the count by the total occurances
double sum = 0;
for (int z = 0; z < apriori[i][j].length; z++)
sum += apriori[i][j][z];
for (int z = 0; z < apriori[i][j].length; z++)
apriori[i][j][z] /= sum;
latch.countDown();
}
}
private Vec getSampleVariableVector(ClassificationDataSet dataSet, int category, int j)
{
Vec vals = dataSet.getSampleVariableVector(category, j);
if(sparceInput)
{
List<Double> nonZeroVals = new DoubleList();
for(int i = 0; i < vals.length(); i++)
if(vals.get(i) != 0)
nonZeroVals.add(vals.get(i));
vals = new DenseVector(nonZeroVals);
}
return vals;
}
@Override
public void train(ClassificationDataSet dataSet, boolean parallel)
{
int nCat = dataSet.getPredicting().getNumOfCategories();
apriori = new double[nCat][dataSet.getNumCategoricalVars()][];
distributions = new ContinuousDistribution[nCat][dataSet.getNumNumericalVars()] ;
priors = dataSet.getPriors();
int totalWorkers = nCat*(dataSet.getNumNumericalVars() + dataSet.getNumCategoricalVars());
CountDownLatch latch = new CountDownLatch(totalWorkers);
ExecutorService threadPool = ParallelUtils.getNewExecutor(parallel);
//Go through each classification
for(int i = 0; i < nCat; i++)
{
//Set ditribution for the numerical values
for(int j = 0; j < dataSet.getNumNumericalVars(); j++)
{
Runnable rn = new DistributionSelectRunable(i, j, getSampleVariableVector(dataSet, i, j), latch);
threadPool.submit(rn);
}
List<DataPoint> dataSamples = dataSet.getSamples(i);
//Iterate through the categorical variables
for(int j = 0; j < dataSet.getNumCategoricalVars(); j++)
{
apriori[i][j] = new double[dataSet.getCategories()[j].getNumOfCategories()];
//Laplace correction, put in an extra occurance for each variable
for(int z = 0; z < apriori[i][j].length; z++)
apriori[i][j][z] = 1;
Runnable rn = new AprioriCounterRunable(i, j, dataSamples, latch);
threadPool.submit(rn);
}
}
//Wait for all the threads to finish
try
{
latch.await();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
finally
{
threadPool.shutdownNow();
}
}
}
| 15,098 | 32.553333 | 148 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/NaiveBayesUpdateable.java | package jsat.classifiers.bayesian;
import java.util.Arrays;
import jsat.classifiers.*;
import jsat.distributions.Normal;
import jsat.exceptions.UntrainedModelException;
import jsat.linear.IndexValue;
import jsat.linear.Vec;
import jsat.math.OnLineStatistics;
import static java.lang.Math.*;
import jsat.math.MathTricks;
/**
* An implementation of Gaussian Naive Bayes that can be updated in an online
* fashion. The ability to be updated comes at the cost to slower training and
* classification time. However NB is already very fast, so the difference is
* not significant. <br>
* The more advanced distribution detection of {@link NaiveBayes} is not
* possible in online form.
*
* @author Edward Raff
*/
public class NaiveBayesUpdateable extends BaseUpdateableClassifier
{
private static final long serialVersionUID = 1835073945715343486L;
/**
* Counts for each option
*/
private double[][][] apriori;
/**
* Online stats about the variable values
*/
private OnLineStatistics[][] valueStats;
private double priorSum = 0;
private double[] priors;
/**
* Handles how vectors are handled. If true, it is assumed vectors are sparce - and zero values will be ignored when training and classifying.
*/
private boolean sparseInput = true;
/**
* Creates a new Naive Bayes classifier that assumes sparce input vectors
*/
public NaiveBayesUpdateable()
{
this(true);
}
/**
* Creates a new Naive Bayes classifier
* @param sparse whether or not to assume input vectors are sparce
*/
public NaiveBayesUpdateable(boolean sparse)
{
setSparse(sparse);
}
/**
* Copy Constructor
* @param other the classifier to make a copy of
*/
protected NaiveBayesUpdateable(NaiveBayesUpdateable other)
{
this(other.sparseInput);
if(other.apriori != null)
{
this.apriori = new double[other.apriori.length][][];
this.valueStats = new OnLineStatistics[other.valueStats.length][];
for(int i = 0; i < other.apriori.length; i++)
{
this.apriori[i] = new double[other.apriori[i].length][];
for(int j = 0; j < other.apriori[i].length; j++)
this.apriori[i][j] = Arrays.copyOf(other.apriori[i][j],
other.apriori[i][j].length);
this.valueStats[i] = new OnLineStatistics[other.valueStats[i].length];
for(int j = 0; j < this.valueStats[i].length; j++)
this.valueStats[i][j] = new OnLineStatistics(other.valueStats[i][j]);
}
this.priorSum = other.priorSum;
this.priors = Arrays.copyOf(other.priors, other.priors.length);
}
}
@Override
public NaiveBayesUpdateable clone()
{
return new NaiveBayesUpdateable(this);
}
@Override
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting)
{
int nCat = predicting.getNumOfCategories();
apriori = new double[nCat][categoricalAttributes.length][];
valueStats = new OnLineStatistics[nCat][numericAttributes];
priors = new double[nCat];
priorSum = nCat;
Arrays.fill(priors, 1.0);
for (int i = 0; i < nCat; i++)
{
//Iterate through the categorical variables
for (int j = 0; j < categoricalAttributes.length; j++)
{
apriori[i][j] = new double[categoricalAttributes[j].getNumOfCategories()];
//Laplace correction, put in an extra occurance for each variable
for (int z = 0; z < apriori[i][j].length; z++)
apriori[i][j][z] = 1;
}
for(int j = 0; j < numericAttributes; j++)
valueStats[i][j] = new OnLineStatistics();
}
}
@Override
public void update(DataPoint dataPoint, double weight, int targetClass)
{
Vec x = dataPoint.getNumericalValues();
if (sparseInput)
for (IndexValue iv : x)
valueStats[targetClass][iv.getIndex()].add(iv.getValue(), weight);
else
for (int j = 0; j < x.length(); j++)
valueStats[targetClass][j].add(x.get(j), weight);
//Categorical value updates
int[] catValues = dataPoint.getCategoricalValues();
for(int j = 0; j < apriori[targetClass].length; j++)
apriori[targetClass][j][catValues[j]]++;
priorSum++;
priors[targetClass]++;
}
@Override
public CategoricalResults classify(DataPoint data)
{
if(apriori == null)
throw new UntrainedModelException("Model has not been intialized");
CategoricalResults results = new CategoricalResults(apriori.length);
double[] logProbs = new double[apriori.length];
double maxLogProg = Double.NEGATIVE_INFINITY;
Vec numVals = data.getNumericalValues();
for( int i = 0; i < valueStats.length; i++)
{
double logProb = 0;
if(sparseInput)
{
for(IndexValue iv : numVals)
{
int indx = iv.getIndex();
double mean = valueStats[i][indx].getMean();
double stndDev = valueStats[i][indx].getStandardDeviation();
double logPDF = Normal.logPdf(iv.getValue(), mean, stndDev);
if(Double.isNaN(logPDF))
logProb += Math.log(1e-16);
else if(Double.isInfinite(logPDF))//Avoid propigation -infinty when the probability is zero
logProb += Math.log(1e-16);
else
logProb += logPDF;
}
}
else
{
for(int j = 0; j < valueStats[i].length; j++)
{
double mean = valueStats[i][j].getMean();
double stdDev = valueStats[i][j].getStandardDeviation();
double logPDF = Normal.logPdf(numVals.get(j), mean, stdDev);
if(Double.isInfinite(logPDF))//Avoid propigation -infinty when the probability is zero
logProb += Math.log(1e-16);//
else
logProb += logPDF;
}
}
//the i goes up to the number of categories, same for aprioror
for(int j = 0; j < apriori[i].length; j++)
{
double sum = 0;
for(int z = 0; z < apriori[i][j].length; z++)
sum += apriori[i][j][z];
double p = apriori[i][j][data.getCategoricalValue(j)];
logProb += Math.log(p/sum);
}
logProb += Math.log(priors[i]/priorSum);
logProbs[i] = logProb;
maxLogProg = Math.max(maxLogProg, logProb);
}
double denom =MathTricks.logSumExp(logProbs, maxLogProg);
for(int i = 0; i < results.size(); i++)
results.setProb(i, exp(logProbs[i]-denom));
results.normalize();
return results;
}
@Override
public boolean supportsWeightedData()
{
return true;
}
/**
* Returns <tt>true</tt> if the input is assume sparse
* @return <tt>true</tt> if the input is assume sparse
*/
public boolean isSparseInput()
{
return sparseInput;
}
/**
* Sets whether or not that classifier should behave as if the input vectors
* are sparse. This means zero values in the input will be ignored when
* performing classification.
*
* @param sparseInput <tt>true</tt> to use a sparse model
*/
public void setSparse(boolean sparseInput)
{
this.sparseInput = sparseInput;
}
}
| 8,101 | 33.476596 | 148 | java |
JSAT | JSAT-master/JSAT/src/jsat/classifiers/bayesian/ODE.java | package jsat.classifiers.bayesian;
import java.util.Arrays;
import jsat.classifiers.*;
import jsat.exceptions.FailedToFitException;
/**
* One-Dependence Estimators (ODE) is an extension of Naive Bayes that, instead
* of assuming all features are independent, assumes all features are dependent
* on one other feature besides the target class. Because of this extra
* dependence requirement, the implementation only allows for categorical
* features.
* <br>
* This class is primarily for use by {@link AODE}
* <br><br>
* See: Webb, G., & Boughton, J. (2005). <i>Not so naive bayes: Aggregating
* one-dependence estimators</i>. Machine Learning, 1–24. Retrieved from
* <a href="http://www.springerlink.com/index/U8W306673M1P866K.pdf">here</a>
*
* @author Edward Raff
*/
public class ODE extends BaseUpdateableClassifier
{
private static final long serialVersionUID = -7732070257669428977L;
/**
* The attribute we will be dependent on
*/
protected int dependent;
/**
* The number of possible values in the target class
*/
protected int predTargets;
/**
* The number of possible values for the dependent variable
*/
protected int depTargets;
/**
* First index is the number of target values <br>
* 2nd index is the number of values for the dependent variable <br>
* 3rd is the number of categorical variables, including the dependent one <br>
* 4th is the count for the variable value <br>
*/
protected double[][][][] counts;
/**
* The prior probability of each combination of target and dependent variable
*/
protected double[][] priors;
protected double priorSum;
/**
* Creates a new ODE classifier
* @param dependent the categorical feature to be dependent of
*/
public ODE(int dependent)
{
this.dependent = dependent;
}
/**
* Copy constructor
* @param toClone the ODE to copy
*/
protected ODE(ODE toClone)
{
this(toClone.dependent);
this.predTargets = toClone.predTargets;
this.depTargets = toClone.depTargets;
if (toClone.counts != null)
{
this.counts = new double[toClone.counts.length][][][];
for (int i = 0; i < this.counts.length; i++)
{
this.counts[i] = new double[i][][];
for (int j = 0; j < this.counts[i].length; j++)
{
this.counts[i][j] = new double[toClone.counts[i][j].length][];
for (int z = 0; z < this.counts[i][j].length; z++)
{
this.counts[i][j][z] =
Arrays.copyOf(toClone.counts[i][j][z],
toClone.counts[i][j][z].length);
}
}
}
this.priors = new double[toClone.priors.length][];
for(int i = 0; i < this.priors.length; i++)
this.priors[i] = Arrays.copyOf(toClone.priors[i], toClone.priors[i].length);
this.priorSum = toClone.priorSum;
}
}
@Override
public CategoricalResults classify(DataPoint data)
{
CategoricalResults cr = new CategoricalResults(predTargets);
int[] catVals = data.getCategoricalValues();
for (int c = 0; c < predTargets; c++)
{
double logProb = getLogPrb(catVals, c);
cr.setProb(c, Math.exp(logProb));
}
cr.normalize();
return cr;
}
@Override
public boolean supportsWeightedData()
{
return true;
}
@Override
public ODE clone()
{
return new ODE(this);
}
@Override
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting)
{
if(categoricalAttributes.length < 1)
throw new FailedToFitException("At least 2 categorical varaibles are needed for ODE");
CategoricalData[] catData = categoricalAttributes;
predTargets = predicting.getNumOfCategories();
depTargets = catData[dependent].getNumOfCategories();
counts = new double[predTargets][depTargets][catData.length][];
for(int i = 0; i < counts.length; i++)
for(int j = 0; j < counts[i].length; j++)
for(int z = 0; z < counts[i][j].length; z++)
{
counts[i][j][z] = new double[catData[z].getNumOfCategories()];
Arrays.fill(counts[i][j][z], 1.0);//Fill will laplace
}
priors = new double[predTargets][depTargets];
for(int i = 0; i < priors.length; i++)
{
Arrays.fill(priors[i], 1.0);
priorSum += priors[i].length;
}
}
@Override
public void update(DataPoint dataPoint, double weight, int targetClass)
{
int[] catVals = dataPoint.getCategoricalValues();
for (int j = 0; j < catVals.length; j++)
if (j == dependent)
continue;
else
counts[targetClass][catVals[dependent]][j][catVals[j]] += weight;
priors[targetClass][catVals[dependent]] += weight;
priorSum += weight;
}
/**
*
* @param catVals the catigorical values for a data point
* @param c the target value to get the probability of
* @return the non normalized log probability of the data point belonging to
* the target class <tt>c</tt>
*/
protected double getLogPrb(int[] catVals, int c)
{
double logProb = 0.0;
int xi = catVals[dependent];
for (int j = 0; j < catVals.length; j++)
{
if(j == dependent)
continue;
double sum = 0;
for(int z = 0; z < counts[c][xi][j].length; z++)
sum += counts[c][xi][j][z];
logProb += Math.log(counts[c][xi][j][catVals[j]]/sum);
}
return logProb + Math.log(priors[c][xi]/priorSum);
}
}
| 6,120 | 32.086486 | 113 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.