001package org.clafer.ir.analysis.deduction;
002
003import java.util.Collection;
004import java.util.HashMap;
005import java.util.HashSet;
006import java.util.Map;
007import java.util.Set;
008import org.clafer.collection.Pair;
009import org.clafer.common.UnsatisfiableException;
010import org.clafer.domain.Domain;
011import org.clafer.ir.IllegalIntException;
012import org.clafer.ir.IllegalSetException;
013import org.clafer.ir.IllegalStringException;
014import org.clafer.ir.IrAcyclic;
015import org.clafer.ir.IrAdd;
016import org.clafer.ir.IrAllDifferent;
017import org.clafer.ir.IrAnd;
018import org.clafer.ir.IrArrayEquality;
019import org.clafer.ir.IrArrayToSet;
020import org.clafer.ir.IrBoolChannel;
021import org.clafer.ir.IrBoolExpr;
022import org.clafer.ir.IrBoolVar;
023import org.clafer.ir.IrCard;
024import org.clafer.ir.IrCompare;
025import org.clafer.ir.IrCount;
026import org.clafer.ir.IrElement;
027import org.clafer.ir.IrIfOnlyIf;
028import org.clafer.ir.IrIntChannel;
029import org.clafer.ir.IrIntVar;
030import org.clafer.ir.IrJoinFunction;
031import org.clafer.ir.IrJoinRelation;
032import org.clafer.ir.IrMember;
033import org.clafer.ir.IrMinus;
034import org.clafer.ir.IrModule;
035import org.clafer.ir.IrMul;
036import org.clafer.ir.IrNot;
037import org.clafer.ir.IrNotMember;
038import org.clafer.ir.IrOffset;
039import org.clafer.ir.IrSelectN;
040import org.clafer.ir.IrSetDifference;
041import org.clafer.ir.IrSetElement;
042import org.clafer.ir.IrSetEquality;
043import org.clafer.ir.IrSetMin;
044import org.clafer.ir.IrSetTernary;
045import org.clafer.ir.IrSetUnion;
046import org.clafer.ir.IrSetVar;
047import org.clafer.ir.IrSingleton;
048import org.clafer.ir.IrSortSets;
049import org.clafer.ir.IrSortStrings;
050import org.clafer.ir.IrSortStringsChannel;
051import org.clafer.ir.IrStringCompare;
052import org.clafer.ir.IrStringVar;
053import org.clafer.ir.IrSubsetEq;
054import org.clafer.ir.IrTernary;
055import org.clafer.ir.IrVar;
056
057/**
058 * Feasibility-based bounds tightening.
059 *
060 * In addition, removes some non-bounds as well and coalesces variables when
061 * possible.
062 *
063 * @author jimmy
064 */
065public class FBBT {
066
067    private final Map<Class<?>, BoolDeducer<?>> boolDeducers;
068    private final Map<Class<?>, IntDeducer<?>> intDeducers;
069    private final Map<Class<?>, SetDeducer<?>> setDeducers;
070
071    public FBBT() {
072        boolDeducers = new HashMap<>();
073        boolDeducers.put(IrAcyclic.class, new AcyclicDeducer());
074        boolDeducers.put(IrAllDifferent.class, new AllDifferentDeducer());
075        boolDeducers.put(IrAnd.class, new AndDeducer());
076        boolDeducers.put(IrArrayEquality.class, new ArrayEqualityDeducer());
077        boolDeducers.put(IrBoolChannel.class, new BoolChannelDeducer());
078        boolDeducers.put(IrBoolVar.class, new BoolVarDeducer());
079        boolDeducers.put(IrCompare.class, new CompareDeducer());
080        boolDeducers.put(IrIfOnlyIf.class, new IfOnlyIfDeducer());
081        boolDeducers.put(IrIntChannel.class, new IntChannelDeducer());
082        boolDeducers.put(IrMember.class, new MemberDeducer());
083        boolDeducers.put(IrNot.class, new NotDeducer());
084        boolDeducers.put(IrNotMember.class, new NotMemberDeducer());
085        boolDeducers.put(IrSelectN.class, new SelectNDeducer());
086        boolDeducers.put(IrSetEquality.class, new SetEqualityDeducer());
087        boolDeducers.put(IrStringCompare.class, new StringCompareDeducer());
088        boolDeducers.put(IrSortSets.class, new SortSetsDeducer());
089        boolDeducers.put(IrSortStrings.class, new SortStringsDeducer());
090        boolDeducers.put(IrSortStringsChannel.class, new SortStringsChannelDeducer());
091        boolDeducers.put(IrSubsetEq.class, new SubsetEqDeducer());
092        intDeducers = new HashMap<>();
093        intDeducers.put(IrAdd.class, new AddDeducer());
094        intDeducers.put(IrCard.class, new CardDeducer());
095        intDeducers.put(IrCount.class, new CountDeducer());
096        intDeducers.put(IrElement.class, new ElementDeducer());
097        intDeducers.put(IrMinus.class, new MinusDeducer());
098        intDeducers.put(IrMul.class, new MulDeducer());
099        intDeducers.put(IrSetMin.class, new SetMinDeducer());
100        intDeducers.put(IrTernary.class, new TernaryDeducer());
101        setDeducers = new HashMap<>();
102        setDeducers.put(IrArrayToSet.class, new ArrayToSetDeducer());
103        setDeducers.put(IrJoinFunction.class, new JoinFunctionDeducer());
104        setDeducers.put(IrJoinRelation.class, new JoinRelationDeducer());
105        setDeducers.put(IrOffset.class, new OffsetDeducer());
106        setDeducers.put(IrSetDifference.class, new SetDifferenceDeducer());
107        setDeducers.put(IrSetElement.class, new SetElementDeducer());
108        setDeducers.put(IrSetTernary.class, new SetTernaryDeducer());
109        setDeducers.put(IrSetUnion.class, new SetUnionDeducer());
110        setDeducers.put(IrSingleton.class, new SingletonDeducer());
111    }
112
113    public Pair<Coalesce, IrModule> propagate(IrModule module) {
114        try {
115            Set<IrBoolExpr> changed = new HashSet<>();
116            changed.addAll(module.getConstraints());
117            State state = new State(module);
118
119            Coalesce coalesce = propagateImpl(state, changed);
120            Coalesce cur = coalesce;
121            while (!cur.isEmpty()) {
122                cur = propagateImpl(state, changed);
123                coalesce = coalesce.compose(cur);
124            }
125            return new Pair<>(coalesce, state.toModule());
126        } catch (IllegalIntException | IllegalSetException | IllegalStringException e) {
127            throw new UnsatisfiableException(e);
128        }
129    }
130
131    private Coalesce propagate(Deduction deduction, State state) {
132        try {
133            Coalesce coalesce = deduction.apply(state.setVars, state.stringVars);
134
135            if (coalesce.isEmpty()) {
136                return coalesce;
137            }
138
139            Set<IrBoolExpr> changed = new HashSet<>();
140            state.apply(coalesce, changed);
141
142            Coalesce cur = coalesce;
143            while (!cur.isEmpty()) {
144                cur = propagateImpl(state, changed);
145                coalesce = coalesce.compose(cur);
146            }
147            return coalesce;
148        } catch (IllegalIntException | IllegalSetException | IllegalStringException e) {
149            throw new UnsatisfiableException(e);
150        }
151    }
152
153    private Coalesce propagateImpl(State state, Set<IrBoolExpr> changed) {
154        Deduction deduction = new Deduction(boolDeducers, intDeducers, setDeducers);
155
156        changed.forEach(deduction::tautology);
157
158        assert deduction.checkInvariants();
159
160        Coalesce coalesce = deduction.apply(state.setVars, state.stringVars);
161
162        if (coalesce.isEmpty()) {
163            return coalesce;
164        }
165
166        changed.clear();
167        state.apply(coalesce, changed);
168
169        return coalesce;
170    }
171
172    public Pair<Coalesce, IrModule> constructiveDisjunction(IrBoolExpr case1, IrBoolExpr case2, IrModule module) {
173        Deduction deduction = new Deduction(boolDeducers, intDeducers, setDeducers);
174
175        module.getConstraints().forEach(deduction::tautology);
176
177        assert deduction.checkInvariants();
178
179        try {
180            Deduction case1Deduction = new Deduction(deduction);
181            case1Deduction.tautology(case1);
182            Coalesce coalesce1 = propagate(case1Deduction, new State(module, case1));
183            try {
184                Deduction case2Deduction = new Deduction(deduction);
185                case2Deduction.tautology(case2);
186                Coalesce coalesce2 = propagate(case2Deduction, new State(module, case2));
187
188                coalesce1.forEachIntVar((key, value1) -> {
189                    IrIntVar value2 = coalesce2.get(key);
190                    if (value2 != key) {
191                        Domain combine = value1.getDomain().union(value2.getDomain());
192                        deduction.within(key, combine);
193                    }
194                });
195
196                coalesce1.forEachSetVar((key, value1) -> {
197                    IrSetVar value2 = coalesce2.get(key);
198                    if (value2 != key) {
199                        Domain combineKer = value1.getKer().intersection(value2.getKer());
200                        Domain combineEnv = value1.getEnv().union(value2.getEnv());
201                        Domain combineCard = value1.getCard().union(value2.getCard());
202                        deduction.kerContains(key, combineKer);
203                        deduction.envSubsetOf(key, combineEnv);
204                        deduction.cardWithin(key, combineCard);
205                    }
206                });
207            } catch (UnsatisfiableException e) {
208                deduction.contradiction(case2);
209            }
210        } catch (UnsatisfiableException e) {
211            deduction.contradiction(case1);
212        }
213        State state = new State(module);
214        Coalesce coalesce = propagate(deduction, state);
215        return new Pair<>(coalesce, state.toModule());
216    }
217
218    private static class State {
219
220        final IrBoolExpr[] constraints;
221        int size;
222        Set<IrSetVar> setVars = new HashSet<>();
223        Set<IrStringVar> stringVars = new HashSet<>();
224        Set<IrSetVar> reuseSetVars = new HashSet<>();
225        Set<IrStringVar> reuseStringVars = new HashSet<>();
226
227        State(IrModule module, IrBoolExpr tautology) {
228            Collection<IrBoolExpr> c = module.getConstraints();
229            if (tautology == null) {
230                this.constraints = c.toArray(new IrBoolExpr[c.size()]);
231            } else {
232                this.constraints = c.toArray(new IrBoolExpr[c.size() + 1]);
233                this.constraints[c.size()] = tautology;
234            }
235            this.size = constraints.length;
236            Set<IrVar> vars = module.getVariables();
237            for (IrVar var : vars) {
238                if (!var.isConstant()) {
239                    if (var instanceof IrSetVar) {
240                        setVars.add((IrSetVar) var);
241                    } else if (var instanceof IrStringVar) {
242                        stringVars.add((IrStringVar) var);
243                    }
244                }
245            }
246        }
247
248        State(IrModule module) {
249            this(module, null);
250        }
251
252        void apply(Coalesce coalesce, Set<IrBoolExpr> changed) {
253            for (int i = 0; i < size;) {
254                IrBoolExpr newConstraint = coalesce.rewrite(constraints[i], null);
255                if (newConstraint.getDomain().isFalse()) {
256                    throw new UnsatisfiableException();
257                } else if (newConstraint.getDomain().isTrue()) {
258                    size--;
259                    constraints[i] = constraints[size];
260                    constraints[size] = null;
261                } else {
262                    if (constraints[i] != newConstraint) {
263                        changed.add(newConstraint);
264                        constraints[i] = newConstraint;
265                    }
266                    i++;
267                }
268            }
269
270            setVars.forEach(x -> reuseSetVars.add((IrSetVar) coalesce.rewrite(x, null)));
271            Set<IrSetVar> tempSetVars = setVars;
272            setVars = reuseSetVars;
273            reuseSetVars = tempSetVars;
274            reuseSetVars.clear();
275
276            stringVars.forEach(x -> reuseStringVars.add((IrStringVar) coalesce.rewrite(x, null)));
277            Set<IrStringVar> tempStringVars = stringVars;
278            stringVars = reuseStringVars;
279            reuseStringVars = tempStringVars;
280            reuseStringVars.clear();
281        }
282
283        IrModule toModule() {
284            IrModule module = new IrModule();
285            for (int i = 0; i < size; i++) {
286                module.addConstraints(constraints[i]);
287            }
288            return module;
289        }
290    }
291}