Commit 7735fabd authored by Daniel Le Berre's avatar Daniel Le Berre

Fixing more sonar violations.

parent 9b19f30d
......@@ -35,10 +35,10 @@ public class Domains {
private static Domains instance;
/** a mapping used to store "full domains", that is domains that contain all integer values between their bounds */
private Map<Integer, Map<Integer, Domain>> fullDomains = new HashMap<Integer, Map<Integer, Domain>>();
private Map<Integer, Map<Integer, Domain>> fullDomains = new HashMap<>();
/** a mapping used to store "enum domains", that is domains built from set of values which are not "full domains" */
private Map<Integer, Domain> enumDomains = new HashMap<Integer, Domain>();
private Map<Integer, Domain> enumDomains = new HashMap<>();
private Domains() {
// singleton DP; prevents public instantiation
......@@ -67,7 +67,7 @@ public class Domains {
public Domain getDomain(int minValue, int maxValue) {
Map<Integer, Domain> fromMin = fullDomains.get(minValue);
if(fromMin == null) {
fromMin = new HashMap<Integer, Domain>();
fromMin = new HashMap<>();
fullDomains.put(minValue, fromMin);
}
Domain dom = fromMin.get(maxValue);
......
......@@ -23,6 +23,8 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Script;
......@@ -41,102 +43,100 @@ import org.sat4j.specs.IVec;
*/
public class Predicate implements Clausifiable {
private String expr;
private Encoding encoding;
private final IVec<String> variables = new Vec<String>();
private static Context cx;
private static Scriptable scope;
static {
cx = Context.enter();
scope = cx.initStandardObjects();
try {
URL url = Predicate.class.getResource("predefinedfunctions.js");
cx.evaluateReader(scope, new InputStreamReader(url.openStream()),
"predefinedfunctions.js", 1, null);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
public Predicate() {
}
public void setExpression(String expr) {
this.expr = expr.replaceAll("if\\(", "ite(").replaceAll("([^m])in\\(", "$1inSet(").replaceAll("^in\\(", "inSet(");
}
public void addVariable(String name) {
variables.push(name);
}
public boolean containsVariable(String name) {
for(int i=0; i<variables.size(); ++i) {
if(variables.get(i).equals(name)) return true;
}
return false;
}
private boolean evaluate(int[] values) {
assert values.length == variables.size();
for (int i = 0; i < variables.size(); i++) {
scope.put(variables.get(i), scope, values[i]);
}
Object result = myscript.exec(cx, scope);
return Context.toBoolean(result);
}
public void toClause(ISolver solver, IVec<Var> vscope, IVec<Evaluable> vars)
throws ContradictionException {
if (myscript == null) {
myscript = cx.compileString(expr, "rhino.log", 1, null);
}
if (vscope.size() == 2) {
encoding = BinarySupportEncoding.instance();
} else {
encoding = DirectEncoding.instance();
}
encoding.onInit(solver, vscope);
int[] tuple = new int[vars.size()];
valuemapping.clear();
find(tuple, 0, vscope, vars, solver);
encoding.onFinish(solver, vscope);
}
private final Map<Evaluable, Integer> valuemapping = new HashMap<Evaluable, Integer>();
private Script myscript;
private void find(int[] tuple, int n, IVec<Var> theScope,
IVec<Evaluable> vars, ISolver solver) throws ContradictionException {
if (valuemapping.size() == theScope.size()) {
for (int i = 0; i < tuple.length; i++) {
Evaluable ev = vars.get(i);
Integer value = valuemapping.get(ev);
if (value == null) {
tuple[i] = ev.domain().get(0);
} else {
tuple[i] = value;
}
}
if (evaluate(tuple)) {
encoding.onSupport(solver, theScope, valuemapping);
} else {
encoding.onNogood(solver, theScope, valuemapping);
}
} else {
Var var = theScope.get(n);
Domain domain = var.domain();
for (int i = 0; i < domain.size(); i++) {
valuemapping.put(var, domain.get(i));
find(tuple, n + 1, theScope, vars, solver);
}
valuemapping.remove(var);
}
}
private String expr;
private Encoding encoding;
private final IVec<String> variables = new Vec<>();
private static Context cx;
private static Scriptable scope;
private final Map<Evaluable, Integer> valuemapping = new HashMap<>();
private Script myscript;
static {
cx = Context.enter();
scope = cx.initStandardObjects();
try {
URL url = Predicate.class.getResource("predefinedfunctions.js");
cx.evaluateReader(scope, new InputStreamReader(url.openStream()), "predefinedfunctions.js", 1, null);
} catch (IOException e) {
Logger.getLogger("org.sat4j.csp").log(Level.SEVERE, "Problem with javascript file", e);
}
}
public void setExpression(String expr) {
this.expr = expr.replaceAll("if\\(", "ite(").replaceAll("([^m])in\\(", "$1inSet(").replaceAll("^in\\(",
"inSet(");
}
public void addVariable(String name) {
variables.push(name);
}
public boolean containsVariable(String name) {
for (int i = 0; i < variables.size(); ++i) {
if (variables.get(i).equals(name)) {
return true;
}
}
return false;
}
private boolean evaluate(int[] values) {
assert values.length == variables.size();
for (int i = 0; i < variables.size(); i++) {
scope.put(variables.get(i), scope, values[i]);
}
Object result = myscript.exec(cx, scope);
return Context.toBoolean(result);
}
public void toClause(ISolver solver, IVec<Var> vscope, IVec<Evaluable> vars) throws ContradictionException {
if (myscript == null) {
myscript = cx.compileString(expr, "rhino.log", 1, null);
}
if (vscope.size() == 2) {
encoding = BinarySupportEncoding.instance();
} else {
encoding = DirectEncoding.instance();
}
encoding.onInit(solver, vscope);
int[] tuple = new int[vars.size()];
valuemapping.clear();
find(tuple, 0, vscope, vars, solver);
encoding.onFinish(solver, vscope);
}
private void find(int[] tuple, int n, IVec<Var> theScope, IVec<Evaluable> vars, ISolver solver)
throws ContradictionException {
if (valuemapping.size() == theScope.size()) {
for (int i = 0; i < tuple.length; i++) {
Evaluable ev = vars.get(i);
Integer value = valuemapping.get(ev);
if (value == null) {
tuple[i] = ev.domain().get(0);
} else {
tuple[i] = value;
}
}
if (evaluate(tuple)) {
encoding.onSupport(solver, theScope, valuemapping);
} else {
encoding.onNogood(solver, theScope, valuemapping);
}
} else {
Var var = theScope.get(n);
Domain domain = var.domain();
for (int i = 0; i < domain.size(); i++) {
valuemapping.put(var, domain.get(i));
find(tuple, n + 1, theScope, vars, solver);
}
valuemapping.remove(var);
}
}
}
......@@ -94,8 +94,8 @@ public class SolverFactory extends ASolverFactory<ISolver> {
*/
public static <L extends ILits> Solver<DataStructureFactory> newMiniSAT(
DataStructureFactory dsf) {
MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<DataStructureFactory>();
Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(learning, dsf,
MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<>();
Solver<DataStructureFactory> solver = new Solver<>(learning, dsf,
new VarOrderHeap(), new MiniSATRestarts());
learning.setDataStructureFactory(solver.getDSFactory());
learning.setVarActivityListener(solver);
......@@ -113,9 +113,6 @@ public class SolverFactory extends ASolverFactory<ISolver> {
* instance of ASolverFactory.
*/
public static ISolver newDefault() {
// Solver<DataStructureFactory> solver = newMiniSAT(new MixedDataStructureDanielWL());
// solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION);
// return solver;
return newSAT();
}
......
......@@ -59,7 +59,7 @@ public abstract class Supports implements Relation {
assert vars.size() == 0;
assert scope.size() == arity;
int[] tuple = new int[scope.size()];
mtuple = new HashMap<Evaluable, Integer>();
mtuple = new HashMap<>();
lastmatch = -1;
encoding = chooseEncoding(scope);
encoding.onInit(solver, scope);
......
......@@ -41,7 +41,7 @@ public class ComparisonCtrBuilder {
this.intensionCtrEncoder = intensionEnc;
}
public boolean buildCtrAllDifferent(String id, XVarInteger[] list) { // TODO:
public boolean buildCtrAllDifferent(XVarInteger[] list) { // TODO:
// remove
// dependence
// to
......@@ -66,7 +66,7 @@ public class ComparisonCtrBuilder {
XVarInteger[] cleanList = new XVarInteger[varSet.size()];
cleanList = varSet.toArray(cleanList);
if (except.length == 0) {
return buildCtrAllDifferent(id, cleanList);
return buildCtrAllDifferent(cleanList);
}
if (cleanList.length < 2)
return false;
......@@ -121,10 +121,10 @@ public class ComparisonCtrBuilder {
boolean contradictionFound = false;
XVarInteger[][] tMatrix = CtrBuilderUtils.transposeMatrix(matrix);
for (int i = 0; i < matrix.length; ++i) {
contradictionFound |= buildCtrAllDifferent(id, matrix[i]);
contradictionFound |= buildCtrAllDifferent(matrix[i]);
}
for (int i = 0; i < tMatrix.length; ++i) {
contradictionFound |= buildCtrAllDifferent(id, tMatrix[i]);
contradictionFound |= buildCtrAllDifferent(tMatrix[i]);
}
return contradictionFound;
}
......
......@@ -20,6 +20,8 @@ package org.sat4j.csp.constraints3;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.sat4j.core.Vec;
import org.sat4j.csp.Evaluable;
......@@ -41,61 +43,64 @@ import org.xcsp.parser.entries.XVariables.XVarInteger;
*
*/
public class CtrBuilderUtils {
public static XVarInteger[][] transposeMatrix(XVarInteger[][] matrix) {
XVarInteger[][] tMatrix = new XVarInteger[matrix[0].length][matrix.length];
for(int i=0; i<matrix[0].length; ++i) {
for(int j=0; j<matrix.length; ++j) {
for (int i = 0; i < matrix[0].length; ++i) {
for (int j = 0; j < matrix.length; ++j) {
tMatrix[i][j] = matrix[j][i];
}
}
return tMatrix;
}
public static String normalizeCspVarName(String name) { // TODO: remove unnecessary calls to this method
public static String normalizeCspVarName(String name) { // TODO: remove
// unnecessary calls
// to this method
return name;
}
public static IVec<Var> toVarVec(Collection<Var> vars) {
IVec<Var> vec = new Vec<>(vars.size());
for(Var v : vars) {
for (Var v : vars) {
vec.push(v);
}
return vec;
}
public static IVec<Evaluable> toEvaluableVec(Collection<Var> vars) {
IVec<Evaluable> vec = new Vec<>(vars.size());
for(Var v : vars) {
for (Var v : vars) {
vec.push(v);
}
return vec;
}
public static String chainExpressionsForAssociativeOp(String[] exprs, String op) {
StringBuilder exprBuf = new StringBuilder();
exprBuf.append(op).append('(').append(exprs[0]);
for(int i=1; i<exprs.length; ++i) exprBuf.append(',').append(exprs[i]);
for (int i = 1; i < exprs.length; ++i)
exprBuf.append(',').append(exprs[i]);
exprBuf.append(')');
return exprBuf.toString();
}
public static String chainExpressionsAssociative(String[] exprs, String op) {
StringBuilder exprBuff = new StringBuilder();
exprBuff.append(exprs[0]);
for(int i=1; i<exprs.length; ++i) {
for (int i = 1; i < exprs.length; ++i) {
exprBuff.append(op);
exprBuff.append(exprs[i]);
}
return exprBuff.toString();
}
public static boolean buildSumEqOneCstr(IPBSolver solver, Map<String, Var> varmapping, XVarInteger[] list) {
Predicate p = new Predicate();
Vec<Var> scope = new Vec<Var>(list.length);
Vec<Evaluable> vars = new Vec<Evaluable>(list.length);
Vec<Evaluable> vars = new Vec<>(list.length);
String[] toChain = new String[list.length];
for(int i=0; i<list.length; ++i) {
for (int i = 0; i < list.length; ++i) {
XVarInteger var = list[i];
scope.push(varmapping.get(var.id));
vars.push(varmapping.get(var.id));
......@@ -103,32 +108,35 @@ public class CtrBuilderUtils {
p.addVariable(norm);
toChain[i] = norm;
}
p.setExpression("eq("+chainExpressionsForAssociativeOp(toChain, "add")+",1)");
p.setExpression("eq(" + chainExpressionsForAssociativeOp(toChain, "add") + ",1)");
try {
p.toClause(solver, scope, vars);
} catch (ContradictionException e) {
Logger.getLogger("org.sat4j.csp").log(Level.INFO, "Trivial inconsistency", e);
return true;
}
return false;
}
public static TypeOperatorRel strictTypeOperator(TypeOperatorRel op) {
switch(op) {
case GE: return TypeOperatorRel.GT;
case LE: return TypeOperatorRel.LT;
default: return op;
switch (op) {
case GE:
return TypeOperatorRel.GT;
case LE:
return TypeOperatorRel.LT;
default:
return op;
}
}
public static String syntaxTreeRootToString(final XNodeParent<XVarInteger> syntaxTreeRoot) {
final StringBuilder treeToString = new StringBuilder();
fillSyntacticStrBuffer(syntaxTreeRoot, treeToString);
return treeToString.toString();
}
private static void fillSyntacticStrBuffer(final XNode<XVarInteger> child,
final StringBuilder treeToString) {
if(child instanceof XNodeLeaf<?>) {
private static void fillSyntacticStrBuffer(final XNode<XVarInteger> child, final StringBuilder treeToString) {
if (child instanceof XNodeLeaf<?>) {
treeToString.append(CtrBuilderUtils.normalizeCspVarName(child.toString()));
return;
}
......@@ -136,7 +144,7 @@ public class CtrBuilderUtils {
final XNode<XVarInteger>[] sons = ((XNodeParent<XVarInteger>) child).sons;
treeToString.append('(');
fillSyntacticStrBuffer(sons[0], treeToString);
for(int i=1; i<sons.length; ++i) {
for (int i = 1; i < sons.length; ++i) {
treeToString.append(',');
fillSyntacticStrBuffer(sons[i], treeToString);
}
......
......@@ -88,7 +88,7 @@ public class ObjBuilder {
final String varId = x.id;
int[] domain = this.cspToSatEncoder.getCspVarDomain(varId);
final IVecInt literals = new VecInt(domain.length);
final IVec<BigInteger> coeffs = new Vec<BigInteger>(domain.length);
final IVec<BigInteger> coeffs = new Vec<>(domain.length);
for(Integer val : domain) {
literals.push(this.cspToSatEncoder.getSolverVar(varId, val));
coeffs.push(BigInteger.valueOf(val));
......
......@@ -38,7 +38,7 @@ public class StringCondition {
private String asString;
private List<String> vars = new ArrayList<String>();
private List<String> vars = new ArrayList<>();
public StringCondition(ConditionVar condition) {
String varId = ((ConditionVar)condition).x.id();
......
......@@ -33,9 +33,9 @@ import org.sat4j.specs.IteratorInt;
public class BinarySupportEncoding implements Encoding {
private final Map<Integer, IVecInt> supportsa = new HashMap<Integer, IVecInt>();
private final Map<Integer, IVecInt> supportsa = new HashMap<>();
private final Map<Integer, IVecInt> supportsb = new HashMap<Integer, IVecInt>();
private final Map<Integer, IVecInt> supportsb = new HashMap<>();
private static final Encoding INSTANCE = new BinarySupportEncoding();
......
......@@ -35,7 +35,7 @@ import org.sat4j.specs.IteratorInt;
public class GeneralizedSupportEncoding implements Encoding {
private final Map<Set<Integer>, IVecInt> supports = new HashMap<Set<Integer>, IVecInt>();
private final Map<Set<Integer>, IVecInt> supports = new HashMap<>();
private static final Encoding INSTANCE = new GeneralizedSupportEncoding();
......@@ -49,8 +49,7 @@ public class GeneralizedSupportEncoding implements Encoding {
public void onFinish(ISolver solver, IVec<Var> scope)
throws ContradictionException {
// TODO Auto-generated method stub
// nothing to do
}
public void onInit(ISolver solver, IVec<Var> scope) {
......@@ -61,13 +60,13 @@ public class GeneralizedSupportEncoding implements Encoding {
public void onNogood(ISolver solver, IVec<Var> scope,
Map<Evaluable, Integer> tuple) throws ContradictionException {
// nothing to do
}
public void onSupport(ISolver solver, IVec<Var> scope,
Map<Evaluable, Integer> tuple) throws ContradictionException {
for (int i = 0; i < scope.size(); i++) {
Set<Integer> set = new TreeSet<Integer>();
Set<Integer> set = new TreeSet<>();
Var vari = scope.get(i);
for (int j = 0; j < scope.size(); j++) {
if (i != j) {
......@@ -85,7 +84,7 @@ public class GeneralizedSupportEncoding implements Encoding {
Map<Set<Integer>, IVecInt> theSupports) {
if (n == scope.size()) {
for (int j = 0; j < acc.length; j++) {
Set<Integer> set = new TreeSet<Integer>();
Set<Integer> set = new TreeSet<>();
for (int i = 0; i < acc.length; i++)
if (i != j)
set.add(scope.get(i).translate(acc[i]));
......
......@@ -44,10 +44,10 @@ public class CspToPBSolverDecorator implements ICspToSatEncoder {
private final IPBSolver solver;
/** a mapping from the CSP variable names to Sat4j CSP variables */
private final Map<String, Var> varmapping = new LinkedHashMap<String, Var>();
private final Map<String, Var> varmapping = new LinkedHashMap<>();
/** a mapping from a Sat4j CSP variable to the first solver internal variable used to encode it */
private final Map<Var, Integer> firstInternalVarMapping = new LinkedHashMap<Var, Integer>();
private final Map<Var, Integer> firstInternalVarMapping = new LinkedHashMap<>();
public CspToPBSolverDecorator(IPBSolver solver) {
this.solver = solver;
......
......@@ -65,7 +65,7 @@ public class TseitinBasedIntensionCtrEncoder implements IIntensionCtrEncoder {
final IExpression expression = parser.getExpression();
Map<Integer, Integer> map = encodeWithTseitin(expression);
IVecInt vars = new VecInt(map.size());
IVec<BigInteger> coeffs = new Vec<BigInteger>(map.size());
IVec<BigInteger> coeffs = new Vec<>(map.size());
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
vars.push(entry.getValue());
coeffs.push(BigInteger.valueOf(entry.getKey()));
......
......@@ -80,13 +80,13 @@ public class CSPReader extends Reader implements org.sat4j.csp.xml.ICSPCallback
private int currentdomainsize;
private final Map<String, Domain> domainmapping = new HashMap<String, Domain>();
private final Map<String, Domain> domainmapping = new HashMap<>();
private final Map<String, Var> varmapping = new LinkedHashMap<String, Var>();
private final Map<String, Var> varmapping = new LinkedHashMap<>();
private final Map<String, Integer> relmapping = new HashMap<String, Integer>();
private final Map<String, Integer> relmapping = new HashMap<>();
private final Map<String, Clausifiable> predmapping = new HashMap<String, Clausifiable>();
private final Map<String, Clausifiable> predmapping = new HashMap<>();
private int nbvarstocreate;
......@@ -96,9 +96,9 @@ public class CSPReader extends Reader implements org.sat4j.csp.xml.ICSPCallback
private Predicate currentpredicate;
private final IVec<Evaluable> variables = new Vec<Evaluable>();
private final IVec<Evaluable> variables = new Vec<>();
private final IVec<Var> scope = new Vec<Var>();
private final IVec<Var> scope = new Vec<>();
private int nbvars;
......
......@@ -24,6 +24,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
......@@ -74,6 +76,7 @@ public enum ECSPFormat {
/**
* @see ECSPFormat#decoratePrintWriter(PrintWriter)
*/
@Override
public PrintWriter decoratePrintWriter(boolean shouldOnlyDisplayEncoding, PrintWriter pw) {
return pw;
}
......@@ -93,6 +96,7 @@ public enum ECSPFormat {
/**
* @see ECSPFormat#decoratePrintWriter(PrintWriter)
*/
@Override
public PrintWriter decoratePrintWriter(boolean shouldOnlyDisplayEncoding, PrintWriter pw) {
if(shouldOnlyDisplayEncoding) {
return pw;
......@@ -117,6 +121,7 @@ public enum ECSPFormat {
/**
* @see ECSPFormat#decoratePrintWriter(PrintWriter)
*/
@Override
public PrintWriter decoratePrintWriter(boolean shouldOnlyDisplayEncoding, PrintWriter pw) {
return pw;
}
......@@ -194,9 +199,8 @@ public enum ECSPFormat {
return tryToInferXmlTypeFromRootMarkup(line);
}
}
} catch (FileNotFoundException e) {
return UNKNOWN;
} catch (IOException e) {
Logger.getLogger("org.sat4j.csp").log(Level.INFO, "IO issue", e);
return UNKNOWN;
}
return UNKNOWN;
......
......@@ -25,6 +25,8 @@ public class PhaseCommandComponent extends CommandComponent {
*/
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger("org.sat4j.sat");
private String currentPhaseSelectionStrategy;
private JComboBox phaseList;
......@@ -97,11 +99,11 @@ public class PhaseCommandComponent extends CommandComponent {
this.solverController.setPhaseSelectionStrategy(phase);
} catch (ClassNotFoundException e) {
Logger.getLogger("org.sat4j.sat").log(Level.INFO, "Invalid Phase error", e);
LOGGER.log(Level.INFO, "Invalid Phase Class error", e);
} catch (IllegalAccessException e) {
Logger.getLogger("org.sat4j.sat").log(Level.INFO, "Invalid Phase error", e);
LOGGER.log(Level.INFO, "Invalid Phase Access error", e);
} catch (InstantiationException e) {
Logger.getLogger("org.sat4j.sat").log(Level.INFO, "Invalid Phase error", e);
LOGGER.log(Level.INFO, "Invalid Phase Instanciation error", e);
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment