001package org.clafer.math;
002
003import gnu.trove.iterator.TIntObjectIterator;
004import gnu.trove.map.TIntObjectMap;
005import gnu.trove.map.TObjectIntMap;
006import gnu.trove.map.hash.TObjectIntHashMap;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collection;
010import java.util.Collections;
011import java.util.Comparator;
012import java.util.HashMap;
013import java.util.HashSet;
014import java.util.Iterator;
015import java.util.LinkedHashSet;
016import java.util.List;
017import java.util.ListIterator;
018import java.util.Map;
019import java.util.Map.Entry;
020import java.util.Set;
021import org.clafer.collection.Pair;
022import org.clafer.common.Check;
023import org.clafer.domain.BoolDomain;
024import org.clafer.math.LinearEquation.Op;
025import static org.clafer.math.LinearEquation.Op.Equal;
026import static org.clafer.math.LinearEquation.Op.LessThanEqual;
027
028/**
029 * @author jimmy
030 */
031public class LinearSystem {
032
033    private final LinearEquation[] equations;
034
035    public LinearSystem(Collection<LinearEquation> equations) {
036        this(equations.toArray(new LinearEquation[equations.size()]));
037    }
038
039    public LinearSystem(LinearEquation... equations) {
040        this.equations = Check.noNulls(equations);
041    }
042
043    public LinearEquation[] getEquations() {
044        return equations;
045    }
046
047    public LinearSystem addEquations(LinearEquation[] equations) {
048        if (equations.length == 0) {
049            return this;
050        }
051        Set<LinearEquation> newEquations = new LinkedHashSet<>(this.equations.length + equations.length);
052        addAll(newEquations, this.equations);
053        addAll(newEquations, equations);
054        return new LinearSystem(newEquations);
055    }
056
057    public LinearSystem addEquations(Collection<LinearEquation> equations) {
058        if (equations.isEmpty()) {
059            return this;
060        }
061        Set<LinearEquation> newEquations = new LinkedHashSet<>(this.equations.length + equations.size());
062        addAll(newEquations, this.equations);
063        newEquations.addAll(equations);
064        return new LinearSystem(newEquations);
065    }
066
067    /**
068     * Create redundant constraints based on Gauss-Jordan elimination.
069     * "Propagating systems of dense linear integer constraints" by Thibaut
070     * Feydy and Peter J. Stuckey.
071     *
072     * @return a linear system with redundant constraints
073     */
074    public LinearSystem gaussJordanElimination() {
075        if (equations.length == 0) {
076            return this;
077        }
078        Set<Variable> variables = new HashSet<>();
079        int numSlack = 0;
080        for (LinearEquation equation : equations) {
081            if (equation.getOp().equals(Op.LessThanEqual)) {
082                numSlack++;
083            }
084            variables.addAll(Arrays.asList(equation.getLeft().getVariables()));
085        }
086        TObjectIntMap<Variable> variableIds = new TObjectIntHashMap<>();
087        int id = numSlack;
088        Variable[] variableOrder = variables.toArray(new Variable[variables.size()]);
089        Arrays.sort(variableOrder, Comparator.comparing(Variable::getName));
090
091        for (Variable variable : variableOrder) {
092            variableIds.put(variable, id++);
093        }
094        int slack = 0;
095        MatrixBuilder matrix = new MatrixBuilder(equations.length, id);
096        Rational[] column = new Rational[equations.length];
097
098        for (int i = 0; i < matrix.numberOfRows(); i++) {
099            LinearEquation equation = equations[i];
100            if (equation.getOp().equals(Op.LessThanEqual)) {
101                matrix.set(i, slack++, Rational.One);
102            }
103            LinearFunction function = equation.getLeft();
104            for (int j = 0; j < function.getCoefficients().length; j++) {
105                Rational coeffient = function.getCoefficients()[j];
106                int variable = variableIds.get(function.getVariables()[j]);
107                assert matrix.get(i, variable).isZero();
108                matrix.set(i, variable, coeffient);
109            }
110            column[i] = equation.getRight();
111        }
112
113        Matrix a = matrix.toMatrix();
114        Matrix b = new Matrix(column);
115        Matrix p = a.addColumns(Matrix.identity(a.numberOfRows())).gaussJordanElimination()
116                .subColumns(a.numberOfColumns());
117
118        Set<LinearEquation> optimize = new LinkedHashSet<>(equations.length);
119        for (TIntObjectMap<Rational> row : p.multiply(a.addColumns(b)).getRows()) {
120            LinearEquation equation = toEquation(row, id + 1, variableOrder);
121            if (equation != null) {
122                BoolDomain entailed = equation.isEntailed();
123                if (entailed.isUnknown()) {
124                    optimize.add(equation);
125                }
126                // TODO: if entailed.isFalse
127            }
128        }
129        return new LinearSystem(optimize);
130    }
131
132    private static LinearEquation toEquation(TIntObjectMap<Rational> row, int columns, Variable[] variables) {
133        if (row.isEmpty()) {
134            return null;
135        }
136        int slacks = columns - 1 - variables.length;
137        boolean hasSlack = false;
138        List<Rational> cs = new ArrayList<>(row.size() - 1);
139        List<Variable> vs = new ArrayList<>(row.size() - 1);
140
141        Rational right = Rational.Zero;
142        TIntObjectIterator<Rational> iter = row.iterator();
143        for (int i = row.size(); i-- > 0;) {
144            iter.advance();
145            int column = iter.key();
146            Rational r = iter.value();
147            if (column == columns - 1) {
148                right = r;
149            } else if (column < slacks) {
150                assert !hasSlack;
151                assert r.isOne();
152                hasSlack = true;
153            } else {
154                cs.add(r);
155                vs.add(variables[column - slacks]);
156            }
157        }
158        LinearFunction left = new LinearFunction(
159                cs.toArray(new Rational[cs.size()]),
160                vs.toArray(new Variable[vs.size()]),
161                Rational.Zero);
162        return new LinearEquation(left, hasSlack ? LessThanEqual : Equal, right);
163    }
164
165    private static <E> boolean containsAny(Collection<E> set, E[] items) {
166        for (E item : items) {
167            if (set.contains(item)) {
168                return true;
169            }
170        }
171        return false;
172    }
173
174    private static <E> void addAll(Collection<E> set, E[] items) {
175        for (E item : items) {
176            set.add(item);
177        }
178    }
179
180    public LinearSystem equalityElimination() {
181        if (equations.length == 0) {
182            return this;
183        }
184        List<LinearEquation> pool = new ArrayList<>(Arrays.asList(equations));
185
186        HashSet<Variable> touched = new HashSet<>();
187        do {
188            touched.clear();
189
190            List<Variable> assignmentKeys = new ArrayList<>();
191            List<LinearFunction> assignmentValues = new ArrayList<>();
192            Iterator<LinearEquation> iter = pool.iterator();
193            while (iter.hasNext()) {
194                LinearEquation equation = iter.next();
195                if (containsAny(touched, equation.getVariables())) {
196                    continue;
197                }
198                if (Equal.equals(equation.getOp()) && equation.getVariables().length <= 2) {
199                    LinearFunction function = equation.getLeft();
200                    // Find the variable with the coefficient closest to zero.
201                    // Tie break 1: The variable with less occurrences.
202                    // Tie break 2: The variable's name.
203                    Rational min = function.getCoefficients()[0].abs();
204                    Variable left = function.getVariables()[0];
205                    for (int i = 1; i < function.getCoefficients().length; i++) {
206                        Variable v1 = left;
207                        Variable v2 = function.getVariables()[i];
208                        Rational r = function.getCoefficients()[i].abs();
209                        int c = min.compareTo(r);
210                        if (c > 0) {
211                            min = r;
212                            left = v2;
213                        } else if (c == 0 && v1.getName().compareTo(v2.getName()) > 0) {
214                            min = r;
215                            left = v2;
216                        }
217                    }
218                    Rational coefficient = equation.getLeft().getCoefficient(left);
219                    LinearFunction right = new LinearFunction(coefficient, left, equation.getRight()).sub(equation.getLeft()).div(coefficient);
220                    assignmentKeys.add(left);
221                    assignmentValues.add(right);
222                    addAll(touched, equation.getVariables());
223                    iter.remove();
224                }
225            }
226            assert assignmentKeys.size() == assignmentValues.size();
227            if (!assignmentKeys.isEmpty()) {
228                ListIterator<LinearEquation> listIter = pool.listIterator();
229                while (listIter.hasNext()) {
230                    LinearEquation equation = listIter.next();
231                    for (int j = 0; j < assignmentKeys.size(); j++) {
232                        equation = equation.replace(assignmentKeys.get(j), assignmentValues.get(j));
233                    }
234                    if (equation.isEntailed().isTrue()) {
235                        listIter.remove();
236                    } else {
237                        listIter.set(equation);
238                    }
239                }
240            }
241        } while (!touched.isEmpty());
242
243        List<LinearEquation> newEquations = new ArrayList<>(pool.size());
244        for (LinearEquation equation : pool) {
245            switch (equation.getOp()) {
246                case Equal:
247                    LinearFunction left = equation.getLeft();
248                    Rational right = equation.getRight();
249                    newEquations.add(new LinearEquation(left, LessThanEqual, right));
250                    newEquations.add(new LinearEquation(left.minus(), LessThanEqual, right.minus()));
251                    break;
252                case LessThanEqual:
253                    newEquations.add(equation);
254                    break;
255                default:
256                    throw new IllegalStateException();
257            }
258        }
259        return new LinearSystem(newEquations);
260    }
261
262    private void removeEquation(Set<LinearEquation> equations,
263            Map<Variable, TObjectIntMap<LinearEquation>> positiveOccurrences,
264            Map<Variable, TObjectIntMap<LinearEquation>> negativeOccurrences) {
265        for (LinearEquation equation : equations) {
266            LinearFunction left = equation.getLeft();
267            Rational[] coefficients = left.getCoefficients();
268            Variable[] variables = left.getVariables();
269            for (int i = 0; i < coefficients.length; i++) {
270                assert !coefficients[i].isZero();
271                Map<Variable, TObjectIntMap<LinearEquation>> map
272                        = coefficients[i].isPositive() ? positiveOccurrences : negativeOccurrences;
273                TObjectIntMap<LinearEquation> references = map.get(variables[i]);
274                assert references != null;
275                if (references.adjustOrPutValue(equation, -1, 0) == 0) {
276                    references.remove(variables[i]);
277                }
278            }
279        }
280    }
281
282    private void addEquation(
283            LinearEquation equation,
284            Map<Variable, TObjectIntMap<LinearEquation>> positiveOccurrences,
285            Map<Variable, TObjectIntMap<LinearEquation>> negativeOccurrences) {
286        LinearFunction left = equation.getLeft();
287        Rational[] coefficients = left.getCoefficients();
288        Variable[] variables = left.getVariables();
289        for (int i = 0; i < coefficients.length; i++) {
290            assert !coefficients[i].isZero();
291            Map<Variable, TObjectIntMap<LinearEquation>> map
292                    = coefficients[i].isPositive() ? positiveOccurrences : negativeOccurrences;
293            TObjectIntMap<LinearEquation> references = map.get(variables[i]);
294            if (references == null) {
295                references = new TObjectIntHashMap<>();
296                map.put(variables[i], references);
297            }
298            references.adjustOrPutValue(equation, 1, 1);
299        }
300    }
301
302    private static <T> HashSet<T> singletonHashSet(T t) {
303        HashSet<T> set = new HashSet<>();
304        set.add(t);
305        return set;
306    }
307
308    private static int tieBreaker(LinearEquation eq1, LinearEquation eq2) {
309        return eq1.getVariables().length - eq2.getVariables().length;
310    }
311
312    private boolean cost(LinearEquation equation,
313            Map<Variable, Pair<Set<LinearEquation>, Rational>> bestLowBound,
314            Map<Variable, Pair<Set<LinearEquation>, Rational>> bestHighBound,
315            Map<Variable, TObjectIntMap<LinearEquation>> positiveOccurrences,
316            Map<Variable, TObjectIntMap<LinearEquation>> negativeOccurrences) {
317        LinearFunction left = equation.getLeft();
318        Rational[] coefficients = left.getCoefficients();
319        Variable[] variables = left.getVariables();
320        assert left.getConstant().isZero();
321        Rational right = equation.getRight();
322
323        Rational low = left.getLowBound();
324        assert LessThanEqual.equals(equation.getOp());
325        boolean changed = false;
326        for (int i = 0; i < coefficients.length; i++) {
327            Rational ai = coefficients[i];
328            Variable vi = variables[i];
329            assert !ai.isZero();
330            if (ai.isPositive()) {
331                Rational hb = right.sub(low.sub(ai.mul(vi.getLowBound()))).div(ai);
332                Pair<Set<LinearEquation>, Rational> best = bestHighBound.get(vi);
333                if (best == null || best.getSnd().compareTo(hb) > 0) {
334                    bestHighBound.put(vi, new Pair<>(singletonHashSet(equation), hb));
335                    if (best != null) {
336                        removeEquation(best.getFst(), positiveOccurrences, negativeOccurrences);
337                    }
338                    addEquation(equation, positiveOccurrences, negativeOccurrences);
339                    changed = true;
340                } else if (best.getSnd().compareTo(hb) == 0 && best.getFst().size() < 10) {
341                    if (best.getFst().add(equation)) {
342                        addEquation(equation, positiveOccurrences, negativeOccurrences);
343                        changed = true;
344                    }
345                }
346            } else {
347                Rational lb = right.sub(low.sub(ai.mul(vi.getHighBound()))).div(ai);
348                Pair<Set<LinearEquation>, Rational> best = bestLowBound.get(vi);
349                if (best == null || best.getSnd().compareTo(lb) < 0) {
350                    bestLowBound.put(vi, new Pair<>(singletonHashSet(equation), lb));
351                    if (best != null) {
352                        removeEquation(best.getFst(), positiveOccurrences, negativeOccurrences);
353                    }
354                    addEquation(equation, positiveOccurrences, negativeOccurrences);
355                    changed = true;
356                } else if (best.getSnd().compareTo(lb) == 0 && best.getFst().size() < 10) {
357                    if (best.getFst().add(equation)) {
358                        addEquation(equation, positiveOccurrences, negativeOccurrences);
359                        changed = true;
360                    }
361                }
362            }
363        }
364        return changed;
365    }
366
367    /**
368     * Create redundant constraints based on Fourier-Motzkin elimination.
369     * "Propagating systems of dense linear integer constraints" by Thibaut
370     * Feydy and Peter J. Stuckey.
371     *
372     * @return a linear system with redundant constraints
373     */
374    public LinearSystem fourierMotzkinElimination() {
375        if (equations.length == 0) {
376            return this;
377        }
378        // bestLowBound[v] returns the constraint that gives the highest low bound for v
379        Map<Variable, Pair<Set<LinearEquation>, Rational>> bestLowBound = new HashMap<>();
380        // bestLowBound[v] returns the constraint that gives the lowest high bound for v
381        Map<Variable, Pair<Set<LinearEquation>, Rational>> bestHighBound = new HashMap<>();
382        // positiveOccurrences[v] returns the equations where v has a positive coefficient.
383        // Each equation may occur multiple times, treated like a reference count.
384        Map<Variable, TObjectIntMap<LinearEquation>> positiveOccurrences = new HashMap<>();
385        // positiveOccurrences[v] returns the equations where v has a negative coefficient.
386        // Each equation may occur multiple times, treated like a reference count.
387        Map<Variable, TObjectIntMap<LinearEquation>> negativeOccurrences = new HashMap<>();
388
389        for (LinearEquation equation : equations) {
390            switch (equation.getOp()) {
391                case Equal:
392                    LinearFunction left = equation.getLeft();
393                    Rational right = equation.getRight();
394                    cost(new LinearEquation(left, Op.LessThanEqual, right),
395                            bestLowBound, bestHighBound, positiveOccurrences, negativeOccurrences);
396                    cost(new LinearEquation(left.minus(), Op.LessThanEqual, right.minus()),
397                            bestLowBound, bestHighBound, positiveOccurrences, negativeOccurrences);
398                    break;
399                case LessThanEqual:
400                    cost(equation, bestLowBound, bestHighBound, positiveOccurrences, negativeOccurrences);
401                    break;
402                default:
403                    throw new IllegalStateException();
404            }
405        }
406
407        boolean changed;
408        do {
409            changed = false;
410            // Because we are iterating over the map and modifying it at the same time, we
411            // need to copy it first.
412            @SuppressWarnings("unchecked")
413            Entry<Variable, TObjectIntMap<LinearEquation>>[] entries
414                    = (Entry<Variable, TObjectIntMap<LinearEquation>>[]) new Entry<?, ?>[positiveOccurrences.size()];
415            entries = positiveOccurrences.entrySet().toArray(entries);
416            for (Entry<Variable, TObjectIntMap<LinearEquation>> entry : entries) {
417                Variable variable = entry.getKey();
418                TObjectIntMap<LinearEquation> positives = entry.getValue();
419                if (!positives.isEmpty()) {
420                    TObjectIntMap<LinearEquation> negatives = negativeOccurrences.get(variable);
421                    if (negatives != null && !negatives.isEmpty()) {
422                        // Need to copy the set to avoid concurrent modification exception.
423                        for (LinearEquation p : positives.keySet().toArray(new LinearEquation[positives.size()])) {
424                            LinearFunction pLeft = p.getLeft();
425                            Rational[] pCoefficients = pLeft.getCoefficients();
426                            Variable[] pVariables = pLeft.getVariables();
427                            Rational a0 = p.getRight();
428                            Rational ak = pLeft.getCoefficient(variable);
429                            // Need to copy the set to avoid concurrent modification exception.
430                            for (LinearEquation n : negatives.keySet().toArray(new LinearEquation[negatives.size()])) {
431                                LinearFunction nLeft = n.getLeft();
432                                Rational[] nCoefficients = nLeft.getCoefficients();
433                                Variable[] nVariables = nLeft.getVariables();
434                                Rational b0 = n.getRight();
435                                Rational bk = nLeft.getCoefficient(variable);
436
437                                Rational[] newCoefficients = new Rational[pCoefficients.length + nCoefficients.length - 2];
438                                Variable[] newVariables = new Variable[newCoefficients.length];
439
440                                int z = 0;
441                                for (int i = 0; i < pCoefficients.length; i++) {
442                                    if (!variable.equals(pVariables[i])) {
443                                        newCoefficients[z] = pCoefficients[i].mul(bk.minus());
444                                        newVariables[z] = pVariables[i];
445                                        z++;
446                                    }
447                                }
448                                for (int i = 0; i < nCoefficients.length; i++) {
449                                    if (!variable.equals(nVariables[i])) {
450                                        newCoefficients[z] = nCoefficients[i].mul(ak);
451                                        newVariables[z] = nVariables[i];
452                                        z++;
453                                    }
454                                }
455                                assert z == newCoefficients.length;
456                                assert z == newVariables.length;
457
458                                LinearEquation newEquation = new LinearEquation(
459                                        new LinearFunction(newCoefficients, newVariables, Rational.Zero),
460                                        LessThanEqual,
461                                        a0.mul(bk.minus()).add(b0.mul(ak)));
462                                assert !newEquation.getVariableSet().contains(variable);
463                                BoolDomain entailed = newEquation.isEntailed();
464                                if (entailed.isUnknown()) {
465                                    changed |= cost(newEquation, bestLowBound, bestHighBound, positiveOccurrences, negativeOccurrences);
466                                }
467                                // TODO: if entailed.isFalse
468                            }
469                        }
470                    }
471                }
472            }
473        } while (changed);
474
475        Set<LinearEquation> newEquations = new LinkedHashSet<>(
476                bestLowBound.size() + bestHighBound.size());
477        for (Pair<Set<LinearEquation>, ?> b : bestLowBound.values()) {
478            newEquations.add(Collections.min(b.getFst(), LinearSystem::tieBreaker));
479        }
480        for (Pair<Set<LinearEquation>, ?> b : bestHighBound.values()) {
481            newEquations.add(Collections.min(b.getFst(), LinearSystem::tieBreaker));
482        }
483        return new LinearSystem(newEquations);
484    }
485
486    /**
487     * If a &le; b and -b &le; a, then replace with a = b.
488     *
489     * @return a linear system with fewer inequalities
490     */
491    public LinearSystem strengthenInequalities() {
492        if (equations.length == 0) {
493            return this;
494        }
495        Set<LinearEquation> newEquations = new LinkedHashSet<>(equations.length);
496        for (LinearEquation equation : equations) {
497            switch (equation.getOp()) {
498                case LessThanEqual:
499                    LinearFunction left = equation.getLeft();
500                    Rational right = equation.getRight();
501                    if (newEquations.remove(new LinearEquation(left.minus(), LessThanEqual, right.minus()))) {
502                        newEquations.add(new LinearEquation(left, Equal, right));
503                        break;
504                    }
505                // fallthrough
506                case Equal:
507                    newEquations.add(equation);
508                    break;
509                default:
510                    throw new IllegalStateException();
511            }
512        }
513        return new LinearSystem(newEquations);
514    }
515
516    /**
517     * Remove some redundant constraints that are never useful.
518     *
519     * @return a linear system with less redundant constraints
520     */
521    public LinearSystem dominantElimination() {
522        if (equations.length == 0) {
523            return this;
524        }
525        Set<LinearEquation> optimize = new LinkedHashSet<>(Arrays.asList(equations));
526        for (LinearEquation equation : equations) {
527            if (Equal.equals(equation.getOp())) {
528                optimize.remove(new LinearEquation(equation.getLeft(), LessThanEqual, equation.getRight()));
529                optimize.remove(new LinearEquation(equation.getLeft().minus(), LessThanEqual, equation.getRight().minus()));
530            }
531            optimize.removeIf(equation::subsumes);
532        }
533        return optimize.size() == equations.length ? this : new LinearSystem(optimize);
534    }
535
536    @Override
537    public String toString() {
538        StringBuilder result = new StringBuilder();
539        for (LinearEquation equation : equations) {
540            result.append(equation).append('\n');
541        }
542        return result.toString();
543    }
544}