001package org.clafer.compiler;
002
003import java.util.ArrayList;
004import java.util.List;
005import org.chocosolver.solver.Model;
006import org.chocosolver.solver.Solution;
007import org.chocosolver.solver.Solver;
008import org.clafer.choco.ResetKeepsLimits;
009import org.chocosolver.solver.constraints.Constraint;
010import org.chocosolver.solver.search.strategy.Search;
011import org.chocosolver.solver.variables.IntVar;
012import org.clafer.instance.InstanceModel;
013
014/**
015 * Implementation of the guided improvement algorithm.
016 *
017 * @author jimmy
018 */
019public class ClaferMultiObjectiveOptimizerGIA extends AbstractImprovementOptimizer {
020
021    private int count = 0;
022    private boolean more = true;
023    private final int[] optimalValues;
024    // GIA
025    private Solution solution = null;
026    private final List<Constraint> stack = new ArrayList<>();
027    private final IntVar[] bounds;
028    private final Constraint dominate;
029
030    ClaferMultiObjectiveOptimizerGIA(Solver solver, ClaferSolutionMap solutionMap,
031            boolean[] maximizes, IntVar[] scores) {
032        super(solver, solutionMap, maximizes, scores);
033        this.optimalValues = new int[scores.length];
034        this.bounds = new IntVar[scores.length];
035
036        List<IntVar> boundVars = new ArrayList<>(this.bounds.length);
037        List<Constraint> strictlyBetter = new ArrayList<>(this.bounds.length);
038        for (int i = 0; i < this.bounds.length; i++) {
039            IntVar score = scores[i];
040            // TODO: copy the domain from score.
041            IntVar bound = solver.getModel().intVar("bound" + i, score.getLB(), score.getUB());
042            this.bounds[i] = bound;
043            boundVars.add(bound);
044            strictlyBetter.add(solver.getModel().arithm(bound, maximizes[i] ? "<" : ">", score));
045        }
046        this.dominate = or(strictlyBetter, solver.getModel());
047        // Posted later, in find(), so that the solver does not report it as free.
048        this.dominate.ignore();
049        for (int i = 0; i < this.bounds.length; i++) {
050            solver.getModel().arithm(this.bounds[i], maximizes[i] ? "<=" : ">=", scores[i]).post();
051        }
052        if (!boundVars.isEmpty()) {
053            solver.setSearch(Search.sequencer(solver.getSearch(), Search.minDomLBSearch(
054                    boundVars.toArray(new IntVar[boundVars.size()])
055            )));
056        }
057    }
058
059    private static Constraint or(List<Constraint> constraints, Model model) {
060        return constraints.isEmpty()
061                ? model.falseConstraint()
062                : model.or(constraints.toArray(new Constraint[constraints.size()]));
063    }
064
065    private void push(Constraint constraint) {
066        assert !stack.contains(constraint);
067        constraint.post();
068        stack.add(constraint);
069    }
070
071    private void popAll() {
072        stack.forEach(solver.getModel()::unpost);
073        stack.clear();
074    }
075
076    @Override
077    public boolean find() throws ReachedLimitException {
078        if (!more) {
079            return false;
080        }
081        more &= count == 0 ? solveFirst() : solveNext();
082        if (solver.isStopCriterionMet()) {
083            more = false;
084            if (solution != null) {
085                InstanceModel bestInstance = solutionMap.getInstance(solution);
086                int[] bestObjectiveValue = new int[scores.length];
087                for (int i = 0; i < bestObjectiveValue.length; i++) {
088                    bestObjectiveValue[i] = solution.getIntVal(scores[i]);
089                }
090                throw new ReachedLimitBestKnownException(bestInstance, bestObjectiveValue);
091            }
092            throw new ReachedLimitException();
093        }
094        if (more) {
095            for (int i = 0; i < optimalValues.length; i++) {
096                optimalValues[i] = solution.getIntVal(scores[i]);
097            }
098            count++;
099        }
100        return more;
101    }
102
103    /*
104     * Implementation of multiple objective optimization based on discussion here:
105     * https://github.com/chocoteam/choco3/issues/188.
106     */
107    private boolean solveFirst() {
108        assert stack.isEmpty();
109
110        solution = solver.findSolution();
111        if (solution == null) {
112            return false;
113        }
114
115        push(dominate);
116
117        int[] best = new int[scores.length];
118        Solution nextSolution = solution;
119        do {
120            solution = nextSolution;
121            for (int i = 0; i < best.length; i++) {
122                best[i] = scores[i].getValue();
123            }
124
125            for (int i = 0; i < bounds.length; i++) {
126                push(solver.getModel().arithm(bounds[i], maximizes[i] ? ">=" : "<=", best[i]));
127            }
128        } while ((nextSolution = solver.findSolution()) != null);
129        if (solver.isStopCriterionMet()) {
130            return false;
131        }
132        popAll();
133        for (int i = 0; i < bounds.length; i++) {
134            push(solver.getModel().arithm(bounds[i], "=", scores[i]));
135        }
136
137        return true;
138    }
139
140    private boolean solveNext() {
141        popAll();
142        ResetKeepsLimits.reset(solver);
143
144        List<Constraint> strictlyBetter = new ArrayList<>(bounds.length);
145        for (int i = 0; i < bounds.length; i++) {
146            strictlyBetter.add(solver.getModel().arithm(bounds[i], maximizes[i] ? ">" : "<", optimalValues[i]));
147        }
148        or(strictlyBetter, solver.getModel()).post();
149        return solveFirst();
150    }
151
152    @Override
153    public InstanceModel instance() {
154        if (count == 0 || !more) {
155            throw new IllegalStateException("No instances. Did you forget to call find?");
156        }
157        return solutionMap.getInstance(solution);
158    }
159
160    @Override
161    public Solution solution() {
162        return solution;
163    }
164
165    @Override
166    public int[] optimalValues() {
167        if (count == 0) {
168            throw new IllegalStateException("No instances. Did you forget to call find?");
169        }
170        return optimalValues.clone();
171    }
172
173    @Override
174    public int instanceCount() {
175        return count;
176    }
177
178    @Override
179    public Solver getInternalSolver() {
180        return solver;
181    }
182}