001package org.clafer.choco;
002
003import java.util.ArrayList;
004import java.util.List;
005import org.chocosolver.solver.Model;
006import org.chocosolver.solver.Solver;
007import org.chocosolver.util.criteria.Criterion;
008
009/**
010 * Stop criteria, for example a time limit, that survive {@link #reset(Solver)}.
011 * Choco's reset removes them, but the solvers in Clafer reset the search to
012 * find further solutions under the same limits. Choco's solver is final, so
013 * the limits are kept in a hook of its model and the solvers in Clafer reset
014 * through {@link #reset(Solver)} instead of {@link Solver#reset()}.
015 *
016 * A time limit is a deadline: it counts from the call to
017 * {@link #limitTime(Solver, long)}, not from the last reset, because Choco
018 * restarts its clock on reset.
019 *
020 * @author MichaƂ Antkiewicz
021 */
022public final class ResetKeepsLimits {
023
024    private static final String LIMITS_HOOK = ResetKeepsLimits.class.getName();
025
026    private ResetKeepsLimits() {
027    }
028
029    /**
030     * Stop the search once {@code ms} milliseconds have passed, even across
031     * resets.
032     *
033     * @param solver the solver
034     * @param ms the time limit in milliseconds
035     */
036    public static void limitTime(Solver solver, long ms) {
037        long deadline = System.nanoTime() + Math.min(ms, Long.MAX_VALUE / 2_000_000) * 1_000_000;
038        Criterion limit = () -> System.nanoTime() - deadline >= 0;
039        limits(solver.getModel()).add(limit);
040        solver.addStopCriterion(limit);
041    }
042
043    /**
044     * Reset the search and restore the limits set with
045     * {@link #limitTime(Solver, long)}.
046     *
047     * @param solver the solver
048     */
049    public static void reset(Solver solver) {
050        solver.reset();
051        List<Criterion> limits = limits(solver.getModel());
052        solver.addStopCriterion(limits.toArray(new Criterion[limits.size()]));
053    }
054
055    @SuppressWarnings("unchecked")
056    private static List<Criterion> limits(Model model) {
057        List<Criterion> limits = (List<Criterion>) model.getHook(LIMITS_HOOK);
058        if (limits == null) {
059            limits = new ArrayList<>();
060            model.addHook(LIMITS_HOOK, limits);
061        }
062        return limits;
063    }
064}