Rename namespace CVC4 to CVC5. (#6249)
[cvc5.git] / src / theory / arith / normal_form.h
1 /********************* */
2 /*! \file normal_form.h
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Tim King, Morgan Deters, Gereon Kremer
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2021 by the authors listed in the file AUTHORS
8 ** in the top-level source directory and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief [[ Add one-line brief description here ]]
13 **
14 ** [[ Add lengthier description here ]]
15 ** \todo document this file
16 **/
17
18 #include "cvc4_private.h"
19
20 #ifndef CVC4__THEORY__ARITH__NORMAL_FORM_H
21 #define CVC4__THEORY__ARITH__NORMAL_FORM_H
22
23 #include <algorithm>
24
25 #include "base/output.h"
26 #include "expr/node.h"
27 #include "expr/node_self_iterator.h"
28 #include "theory/arith/delta_rational.h"
29 #include "util/rational.h"
30
31 namespace CVC5 {
32 namespace theory {
33 namespace arith {
34
35 /***********************************************/
36 /***************** Normal Form *****************/
37 /***********************************************/
38 /***********************************************/
39
40 /**
41 * Section 1: Languages
42 * The normal form for arithmetic nodes is defined by the language
43 * accepted by the following BNFs with some guard conditions.
44 * (The guard conditions are in Section 3 for completeness.)
45 *
46 * variable := n
47 * where
48 * n.isVar() or is foreign
49 * n.getType() \in {Integer, Real}
50 *
51 * constant := n
52 * where
53 * n.getKind() == kind::CONST_RATIONAL
54 *
55 * var_list := variable | (* [variable])
56 * where
57 * len [variable] >= 2
58 * isSorted varOrder [variable]
59 *
60 * monomial := constant | var_list | (* constant' var_list')
61 * where
62 * \f$ constant' \not\in {0,1} \f$
63 *
64 * polynomial := monomial' | (+ [monomial])
65 * where
66 * len [monomial] >= 2
67 * isStrictlySorted monoOrder [monomial]
68 * forall (\x -> x != 0) [monomial]
69 *
70 * rational_cmp := (|><| qpolynomial constant)
71 * where
72 * |><| is GEQ, or GT
73 * not (exists constantMonomial (monomialList qpolynomial))
74 * (exists realMonomial (monomialList qpolynomial))
75 * abs(monomialCoefficient (head (monomialList qpolynomial))) == 1
76 *
77 * integer_cmp := (>= zpolynomial constant)
78 * where
79 * not (exists constantMonomial (monomialList zpolynomial))
80 * (forall integerMonomial (monomialList zpolynomial))
81 * the gcd of all numerators of coefficients is 1
82 * the denominator of all coefficients and the constant is 1
83 * the leading coefficient is positive
84 *
85 * rational_eq := (= qvarlist qpolynomial)
86 * where
87 * let allMonomials = (cons qvarlist (monomialList zpolynomial))
88 * let variableMonomials = (drop constantMonomial allMonomials)
89 * isStrictlySorted variableMonomials
90 * exists realMonomial variableMonomials
91 * is not empty qvarlist
92 *
93 * integer_eq := (= zmonomial zpolynomial)
94 * where
95 * let allMonomials = (cons zmonomial (monomialList zpolynomial))
96 * let variableMonomials = (drop constantMonomial allMonomials)
97 * not (constantMonomial zmonomial)
98 * (forall integerMonomial allMonomials)
99 * isStrictlySorted variableMonomials
100 * the gcd of all numerators of coefficients is 1
101 * the denominator of all coefficients and the constant is 1
102 * the coefficient of monomial is positive
103 * the value of the coefficient of monomial is minimal in variableMonomials
104 *
105 * comparison := TRUE | FALSE
106 * | rational_cmp | (not rational_cmp)
107 * | rational_eq | (not rational_eq)
108 * | integer_cmp | (not integer_cmp)
109 * | integer_eq | (not integer_eq)
110 *
111 * Normal Form for terms := polynomial
112 * Normal Form for atoms := comparison
113 */
114
115 /**
116 * Section 2: Helper Classes
117 * The langauges accepted by each of these defintions
118 * roughly corresponds to one of the following helper classes:
119 * Variable
120 * Constant
121 * VarList
122 * Monomial
123 * Polynomial
124 * Comparison
125 *
126 * Each of the classes obeys the following contracts/design decisions:
127 * -Calling isMember(Node node) on a node returns true iff that node is a
128 * a member of the language. Note: isMember is O(n).
129 * -Calling isNormalForm() on a helper class object returns true iff that
130 * helper class currently represents a normal form object.
131 * -If isNormalForm() is false, then this object must have been made
132 * using a mk*() factory function.
133 * -If isNormalForm() is true, calling getNode() on all of these classes
134 * returns a node that would be accepted by the corresponding language.
135 * And if isNormalForm() is false, returns Node::null().
136 * -Each of the classes is immutable.
137 * -Public facing constuctors have a 1-to-1 correspondence with one of
138 * production rules in the above grammar.
139 * -Public facing constuctors are required to fail in debug mode when the
140 * guards of the production rule are not strictly met.
141 * For example: Monomial(Constant(1),VarList(Variable(x))) must fail.
142 * -When a class has a Class parseClass(Node node) function,
143 * if isMember(node) is true, the function is required to return an instance
144 * of the helper class, instance, s.t. instance.getNode() == node.
145 * And if isMember(node) is false, this throws an assertion failure in debug
146 * mode and has undefined behaviour if not in debug mode.
147 * -Only public facing constructors, parseClass(node), and mk*() functions are
148 * considered privileged functions for the helper class.
149 * -Only privileged functions may use private constructors, and access
150 * private data members.
151 * -All non-privileged functions are considered utility functions and
152 * must use a privileged function in order to create an instance of the class.
153 */
154
155 /**
156 * Section 3: Guard Conditions Misc.
157 *
158 *
159 * variable_order x y =
160 * if (meta_kind_variable x) and (meta_kind_variable y)
161 * then node_order x y
162 * else if (meta_kind_variable x)
163 * then false
164 * else if (meta_kind_variable y)
165 * then true
166 * else node_order x y
167 *
168 * var_list_len vl =
169 * match vl with
170 * variable -> 1
171 * | (* [variable]) -> len [variable]
172 *
173 * order res =
174 * match res with
175 * Empty -> (0,Node::null())
176 * | NonEmpty(vl) -> (var_list_len vl, vl)
177 *
178 * var_listOrder a b = tuple_cmp (order a) (order b)
179 *
180 * monomialVarList monomial =
181 * match monomial with
182 * constant -> Empty
183 * | var_list -> NonEmpty(var_list)
184 * | (* constant' var_list') -> NonEmpty(var_list')
185 *
186 * monoOrder m0 m1 = var_listOrder (monomialVarList m0) (monomialVarList m1)
187 *
188 * integerMonomial mono =
189 * forall varHasTypeInteger (monomialVarList mono)
190 *
191 * realMonomial mono = not (integerMonomial mono)
192 *
193 * constantMonomial monomial =
194 * match monomial with
195 * constant -> true
196 * | var_list -> false
197 * | (* constant' var_list') -> false
198 *
199 * monomialCoefficient monomial =
200 * match monomial with
201 * constant -> constant
202 * | var_list -> Constant(1)
203 * | (* constant' var_list') -> constant'
204 *
205 * monomialList polynomial =
206 * match polynomial with
207 * monomial -> monomial::[]
208 * | (+ [monomial]) -> [monomial]
209 */
210
211 /**
212 * A NodeWrapper is a class that is a thinly veiled container of a Node object.
213 */
214 class NodeWrapper {
215 private:
216 Node node;
217 public:
218 NodeWrapper(Node n) : node(n) {}
219 const Node& getNode() const { return node; }
220 };/* class NodeWrapper */
221
222
223 class Variable : public NodeWrapper {
224 public:
225 Variable(Node n) : NodeWrapper(n) { Assert(isMember(getNode())); }
226
227 // TODO: check if it's a theory leaf also
228 static bool isMember(Node n)
229 {
230 Kind k = n.getKind();
231 switch (k)
232 {
233 case kind::CONST_RATIONAL: return false;
234 case kind::INTS_DIVISION:
235 case kind::INTS_MODULUS:
236 case kind::DIVISION:
237 case kind::INTS_DIVISION_TOTAL:
238 case kind::INTS_MODULUS_TOTAL:
239 case kind::DIVISION_TOTAL: return isDivMember(n);
240 case kind::IAND: return isIAndMember(n);
241 case kind::EXPONENTIAL:
242 case kind::SINE:
243 case kind::COSINE:
244 case kind::TANGENT:
245 case kind::COSECANT:
246 case kind::SECANT:
247 case kind::COTANGENT:
248 case kind::ARCSINE:
249 case kind::ARCCOSINE:
250 case kind::ARCTANGENT:
251 case kind::ARCCOSECANT:
252 case kind::ARCSECANT:
253 case kind::ARCCOTANGENT:
254 case kind::SQRT:
255 case kind::PI: return isTranscendentalMember(n);
256 case kind::ABS:
257 case kind::TO_INTEGER:
258 // Treat to_int as a variable; it is replaced in early preprocessing
259 // by a variable.
260 return true;
261 default: return isLeafMember(n);
262 }
263 }
264
265 static bool isLeafMember(Node n);
266 static bool isIAndMember(Node n);
267 static bool isDivMember(Node n);
268 bool isDivLike() const{
269 return isDivMember(getNode());
270 }
271 static bool isTranscendentalMember(Node n);
272
273 bool isNormalForm() { return isMember(getNode()); }
274
275 bool isIntegral() const {
276 return getNode().getType().isInteger();
277 }
278
279 bool isMetaKindVariable() const {
280 return getNode().isVar();
281 }
282
283 bool operator<(const Variable& v) const {
284 VariableNodeCmp cmp;
285 return cmp(this->getNode(), v.getNode());
286 }
287
288 struct VariableNodeCmp {
289 static inline int cmp(const Node& n, const Node& m) {
290 if ( n == m ) { return 0; }
291
292 // this is now slightly off of the old variable order.
293
294 bool nIsInteger = n.getType().isInteger();
295 bool mIsInteger = m.getType().isInteger();
296
297 if(nIsInteger == mIsInteger){
298 bool nIsVariable = n.isVar();
299 bool mIsVariable = m.isVar();
300
301 if(nIsVariable == mIsVariable){
302 if(n < m){
303 return -1;
304 }else{
305 Assert(n != m);
306 return 1;
307 }
308 }else{
309 if(nIsVariable){
310 return -1; // nIsVariable => !mIsVariable
311 }else{
312 return 1; // !nIsVariable => mIsVariable
313 }
314 }
315 }else{
316 Assert(nIsInteger != mIsInteger);
317 if(nIsInteger){
318 return 1; // nIsInteger => !mIsInteger
319 }else{
320 return -1; // !nIsInteger => mIsInteger
321 }
322 }
323 }
324
325 bool operator()(const Node& n, const Node& m) const {
326 return VariableNodeCmp::cmp(n,m) < 0;
327 }
328 };
329
330 bool operator==(const Variable& v) const { return getNode() == v.getNode();}
331
332 size_t getComplexity() const;
333 };/* class Variable */
334
335
336 class Constant : public NodeWrapper {
337 public:
338 Constant(Node n) : NodeWrapper(n) { Assert(isMember(getNode())); }
339
340 static bool isMember(Node n) { return n.getKind() == kind::CONST_RATIONAL; }
341
342 bool isNormalForm() { return isMember(getNode()); }
343
344 static Constant mkConstant(Node n)
345 {
346 Assert(n.getKind() == kind::CONST_RATIONAL);
347 return Constant(n);
348 }
349
350 static Constant mkConstant(const Rational& rat);
351
352 static Constant mkZero() {
353 return mkConstant(Rational(0));
354 }
355
356 static Constant mkOne() {
357 return mkConstant(Rational(1));
358 }
359
360 const Rational& getValue() const {
361 return getNode().getConst<Rational>();
362 }
363
364 static int absCmp(const Constant& a, const Constant& b);
365 bool isIntegral() const { return getValue().isIntegral(); }
366
367 int sgn() const { return getValue().sgn(); }
368
369 bool isZero() const { return sgn() == 0; }
370 bool isNegative() const { return sgn() < 0; }
371 bool isPositive() const { return sgn() > 0; }
372
373 bool isOne() const { return getValue() == 1; }
374
375 Constant operator*(const Rational& other) const {
376 return mkConstant(getValue() * other);
377 }
378
379 Constant operator*(const Constant& other) const {
380 return mkConstant(getValue() * other.getValue());
381 }
382 Constant operator+(const Constant& other) const {
383 return mkConstant(getValue() + other.getValue());
384 }
385 Constant operator-() const {
386 return mkConstant(-getValue());
387 }
388
389 Constant inverse() const{
390 Assert(!isZero());
391 return mkConstant(getValue().inverse());
392 }
393
394 bool operator<(const Constant& other) const {
395 return getValue() < other.getValue();
396 }
397
398 bool operator==(const Constant& other) const {
399 //Rely on node uniqueness.
400 return getNode() == other.getNode();
401 }
402
403 Constant abs() const {
404 if(isNegative()){
405 return -(*this);
406 }else{
407 return (*this);
408 }
409 }
410
411 uint32_t length() const{
412 Assert(isIntegral());
413 return getValue().getNumerator().length();
414 }
415
416 size_t getComplexity() const;
417
418 };/* class Constant */
419
420
421 template <class GetNodeIterator>
422 inline Node makeNode(Kind k, GetNodeIterator start, GetNodeIterator end) {
423 NodeBuilder<> nb(k);
424
425 while(start != end) {
426 nb << (*start).getNode();
427 ++start;
428 }
429
430 return Node(nb);
431 }/* makeNode<GetNodeIterator>(Kind, iterator, iterator) */
432
433 /**
434 * A VarList is a sorted list of variables representing a product.
435 * If the VarList is empty, it represents an empty product or 1.
436 * If the VarList has size 1, it represents a single variable.
437 *
438 * A non-sorted VarList can never be successfully made in debug mode.
439 */
440 class VarList : public NodeWrapper {
441 private:
442
443 static Node multList(const std::vector<Variable>& list) {
444 Assert(list.size() >= 2);
445
446 return makeNode(kind::NONLINEAR_MULT, list.begin(), list.end());
447 }
448
449 VarList() : NodeWrapper(Node::null()) {}
450
451 VarList(Node n);
452
453 typedef expr::NodeSelfIterator internal_iterator;
454
455 internal_iterator internalBegin() const {
456 if(singleton()){
457 return expr::NodeSelfIterator::self(getNode());
458 }else{
459 return getNode().begin();
460 }
461 }
462
463 internal_iterator internalEnd() const {
464 if(singleton()){
465 return expr::NodeSelfIterator::selfEnd(getNode());
466 }else{
467 return getNode().end();
468 }
469 }
470
471 public:
472
473 class iterator : public std::iterator<std::input_iterator_tag, Variable> {
474 private:
475 internal_iterator d_iter;
476
477 public:
478 explicit iterator(internal_iterator i) : d_iter(i) {}
479
480 inline Variable operator*() {
481 return Variable(*d_iter);
482 }
483
484 bool operator==(const iterator& i) {
485 return d_iter == i.d_iter;
486 }
487
488 bool operator!=(const iterator& i) {
489 return d_iter != i.d_iter;
490 }
491
492 iterator operator++() {
493 ++d_iter;
494 return *this;
495 }
496
497 iterator operator++(int) {
498 return iterator(d_iter++);
499 }
500 };
501
502 iterator begin() const {
503 return iterator(internalBegin());
504 }
505
506 iterator end() const {
507 return iterator(internalEnd());
508 }
509
510 Variable getHead() const {
511 Assert(!empty());
512 return *(begin());
513 }
514
515 VarList(Variable v) : NodeWrapper(v.getNode()) {
516 Assert(isSorted(begin(), end()));
517 }
518
519 VarList(const std::vector<Variable>& l) : NodeWrapper(multList(l)) {
520 Assert(l.size() >= 2);
521 Assert(isSorted(begin(), end()));
522 }
523
524 static bool isMember(Node n);
525
526 bool isNormalForm() const {
527 return !empty();
528 }
529
530 static VarList mkEmptyVarList() {
531 return VarList();
532 }
533
534
535 /** There are no restrictions on the size of l */
536 static VarList mkVarList(const std::vector<Variable>& l) {
537 if(l.size() == 0) {
538 return mkEmptyVarList();
539 } else if(l.size() == 1) {
540 return VarList((*l.begin()).getNode());
541 } else {
542 return VarList(l);
543 }
544 }
545
546 bool empty() const { return getNode().isNull(); }
547 bool singleton() const {
548 return !empty() && getNode().getKind() != kind::NONLINEAR_MULT;
549 }
550
551 int size() const {
552 if(singleton())
553 return 1;
554 else
555 return getNode().getNumChildren();
556 }
557
558 static VarList parseVarList(Node n);
559
560 VarList operator*(const VarList& vl) const;
561
562 int cmp(const VarList& vl) const;
563
564 bool operator<(const VarList& vl) const { return cmp(vl) < 0; }
565
566 bool operator==(const VarList& vl) const { return cmp(vl) == 0; }
567
568 bool isIntegral() const {
569 for(iterator i = begin(), e=end(); i != e; ++i ){
570 Variable var = *i;
571 if(!var.isIntegral()){
572 return false;
573 }
574 }
575 return true;
576 }
577 size_t getComplexity() const;
578
579 private:
580 bool isSorted(iterator start, iterator end);
581
582 };/* class VarList */
583
584
585 /** Constructors have side conditions. Use the static mkMonomial functions instead. */
586 class Monomial : public NodeWrapper {
587 private:
588 Constant constant;
589 VarList varList;
590 Monomial(Node n, const Constant& c, const VarList& vl):
591 NodeWrapper(n), constant(c), varList(vl)
592 {
593 Assert(!c.isZero() || vl.empty());
594 Assert(c.isZero() || !vl.empty());
595
596 Assert(!c.isOne() || !multStructured(n));
597 }
598
599 static Node makeMultNode(const Constant& c, const VarList& vl) {
600 Assert(!c.isZero());
601 Assert(!c.isOne());
602 Assert(!vl.empty());
603 return NodeManager::currentNM()->mkNode(kind::MULT, c.getNode(), vl.getNode());
604 }
605
606 static bool multStructured(Node n) {
607 return n.getKind() == kind::MULT &&
608 n[0].getKind() == kind::CONST_RATIONAL &&
609 n.getNumChildren() == 2;
610 }
611
612 Monomial(const Constant& c):
613 NodeWrapper(c.getNode()), constant(c), varList(VarList::mkEmptyVarList())
614 { }
615
616 Monomial(const VarList& vl):
617 NodeWrapper(vl.getNode()), constant(Constant::mkConstant(1)), varList(vl)
618 {
619 Assert(!varList.empty());
620 }
621
622 Monomial(const Constant& c, const VarList& vl):
623 NodeWrapper(makeMultNode(c,vl)), constant(c), varList(vl)
624 {
625 Assert(!c.isZero());
626 Assert(!c.isOne());
627 Assert(!varList.empty());
628
629 Assert(multStructured(getNode()));
630 }
631 public:
632 static bool isMember(TNode n);
633
634 /** Makes a monomial with no restrictions on c and vl. */
635 static Monomial mkMonomial(const Constant& c, const VarList& vl);
636
637 /** If vl is empty, this make one. */
638 static Monomial mkMonomial(const VarList& vl);
639
640 static Monomial mkMonomial(const Constant& c){
641 return Monomial(c);
642 }
643
644 static Monomial mkMonomial(const Variable& v){
645 return Monomial(VarList(v));
646 }
647
648 static Monomial parseMonomial(Node n);
649
650 static Monomial mkZero() {
651 return Monomial(Constant::mkConstant(0));
652 }
653 static Monomial mkOne() {
654 return Monomial(Constant::mkConstant(1));
655 }
656 const Constant& getConstant() const { return constant; }
657 const VarList& getVarList() const { return varList; }
658
659 bool isConstant() const {
660 return varList.empty();
661 }
662
663 bool isZero() const {
664 return constant.isZero();
665 }
666
667 bool coefficientIsOne() const {
668 return constant.isOne();
669 }
670
671 bool absCoefficientIsOne() const {
672 return coefficientIsOne() || constant.getValue() == -1;
673 }
674
675 bool constantIsPositive() const {
676 return getConstant().isPositive();
677 }
678
679 Monomial operator*(const Rational& q) const;
680 Monomial operator*(const Constant& c) const;
681 Monomial operator*(const Monomial& mono) const;
682
683 Monomial operator-() const{
684 return (*this) * Rational(-1);
685 }
686
687
688 int cmp(const Monomial& mono) const {
689 return getVarList().cmp(mono.getVarList());
690 }
691
692 bool operator<(const Monomial& vl) const {
693 return cmp(vl) < 0;
694 }
695
696 bool operator==(const Monomial& vl) const {
697 return cmp(vl) == 0;
698 }
699
700 static bool isSorted(const std::vector<Monomial>& m) {
701 return std::is_sorted(m.begin(), m.end());
702 }
703
704 static bool isStrictlySorted(const std::vector<Monomial>& m) {
705 return isSorted(m) && std::adjacent_find(m.begin(),m.end()) == m.end();
706 }
707
708 static void sort(std::vector<Monomial>& m);
709 static void combineAdjacentMonomials(std::vector<Monomial>& m);
710
711 /**
712 * The variable product
713 */
714 bool integralVariables() const {
715 return getVarList().isIntegral();
716 }
717
718 /**
719 * The coefficient of the monomial is integral.
720 */
721 bool integralCoefficient() const {
722 return getConstant().isIntegral();
723 }
724
725 /**
726 * A Monomial is an "integral" monomial if the constant is integral.
727 */
728 bool isIntegral() const {
729 return integralCoefficient() && integralVariables();
730 }
731
732 /** Returns true if the VarList is a product of at least 2 Variables.*/
733 bool isNonlinear() const {
734 return getVarList().size() >= 2;
735 }
736
737 /**
738 * Given a sorted list of monomials, this function transforms this
739 * into a strictly sorted list of monomials that does not contain zero.
740 */
741 //static std::vector<Monomial> sumLikeTerms(const std::vector<Monomial>& monos);
742
743 int absCmp(const Monomial& other) const{
744 return getConstant().getValue().absCmp(other.getConstant().getValue());
745 }
746 // bool absLessThan(const Monomial& other) const{
747 // return getConstant().abs() < other.getConstant().abs();
748 // }
749
750 uint32_t coefficientLength() const{
751 return getConstant().length();
752 }
753
754 void print() const;
755 static void printList(const std::vector<Monomial>& list);
756
757 size_t getComplexity() const;
758 };/* class Monomial */
759
760 class SumPair;
761 class Comparison;;
762
763 class Polynomial : public NodeWrapper {
764 private:
765 bool d_singleton;
766
767 Polynomial(TNode n) : NodeWrapper(n), d_singleton(Monomial::isMember(n)) {
768 Assert(isMember(getNode()));
769 }
770
771 static Node makePlusNode(const std::vector<Monomial>& m) {
772 Assert(m.size() >= 2);
773
774 return makeNode(kind::PLUS, m.begin(), m.end());
775 }
776
777 typedef expr::NodeSelfIterator internal_iterator;
778
779 internal_iterator internalBegin() const {
780 if(singleton()){
781 return expr::NodeSelfIterator::self(getNode());
782 }else{
783 return getNode().begin();
784 }
785 }
786
787 internal_iterator internalEnd() const {
788 if(singleton()){
789 return expr::NodeSelfIterator::selfEnd(getNode());
790 }else{
791 return getNode().end();
792 }
793 }
794
795 bool singleton() const { return d_singleton; }
796
797 public:
798 static bool isMember(TNode n);
799
800 class iterator : public std::iterator<std::input_iterator_tag, Monomial> {
801 private:
802 internal_iterator d_iter;
803
804 public:
805 explicit iterator(internal_iterator i) : d_iter(i) {}
806
807 inline Monomial operator*() {
808 return Monomial::parseMonomial(*d_iter);
809 }
810
811 bool operator==(const iterator& i) {
812 return d_iter == i.d_iter;
813 }
814
815 bool operator!=(const iterator& i) {
816 return d_iter != i.d_iter;
817 }
818
819 iterator operator++() {
820 ++d_iter;
821 return *this;
822 }
823
824 iterator operator++(int) {
825 return iterator(d_iter++);
826 }
827 };
828
829 iterator begin() const { return iterator(internalBegin()); }
830 iterator end() const { return iterator(internalEnd()); }
831
832 Polynomial(const Monomial& m):
833 NodeWrapper(m.getNode()), d_singleton(true)
834 {}
835
836 Polynomial(const std::vector<Monomial>& m):
837 NodeWrapper(makePlusNode(m)), d_singleton(false)
838 {
839 Assert(m.size() >= 2);
840 Assert(Monomial::isStrictlySorted(m));
841 }
842
843 static Polynomial mkPolynomial(const Constant& c){
844 return Polynomial(Monomial::mkMonomial(c));
845 }
846
847 static Polynomial mkPolynomial(const Variable& v){
848 return Polynomial(Monomial::mkMonomial(v));
849 }
850
851 static Polynomial mkPolynomial(const std::vector<Monomial>& m) {
852 if(m.size() == 0) {
853 return Polynomial(Monomial::mkZero());
854 } else if(m.size() == 1) {
855 return Polynomial((*m.begin()));
856 } else {
857 return Polynomial(m);
858 }
859 }
860
861 static Polynomial parsePolynomial(Node n) {
862 return Polynomial(n);
863 }
864
865 static Polynomial mkZero() {
866 return Polynomial(Monomial::mkZero());
867 }
868 static Polynomial mkOne() {
869 return Polynomial(Monomial::mkOne());
870 }
871 bool isZero() const {
872 return singleton() && (getHead().isZero());
873 }
874
875 bool isConstant() const {
876 return singleton() && (getHead().isConstant());
877 }
878
879 bool containsConstant() const {
880 return getHead().isConstant();
881 }
882
883 uint32_t size() const{
884 if(singleton()){
885 return 1;
886 }else{
887 Assert(getNode().getKind() == kind::PLUS);
888 return getNode().getNumChildren();
889 }
890 }
891
892 Monomial getHead() const {
893 return *(begin());
894 }
895
896 Polynomial getTail() const {
897 Assert(!singleton());
898
899 iterator tailStart = begin();
900 ++tailStart;
901 std::vector<Monomial> subrange;
902 std::copy(tailStart, end(), std::back_inserter(subrange));
903 return mkPolynomial(subrange);
904 }
905
906 Monomial minimumVariableMonomial() const;
907 bool variableMonomialAreStrictlyGreater(const Monomial& m) const;
908
909 void printList() const {
910 if(Debug.isOn("normal-form")){
911 Debug("normal-form") << "start list" << std::endl;
912 for(iterator i = begin(), oend = end(); i != oend; ++i) {
913 const Monomial& m =*i;
914 m.print();
915 }
916 Debug("normal-form") << "end list" << std::endl;
917 }
918 }
919
920 /** A Polynomial is an "integral" polynomial if all of the monomials are integral. */
921 bool allIntegralVariables() const {
922 for(iterator i = begin(), e=end(); i!=e; ++i){
923 if(!(*i).integralVariables()){
924 return false;
925 }
926 }
927 return true;
928 }
929
930 /**
931 * A Polynomial is an "integral" polynomial if all of the monomials are integral
932 * and all of the coefficients are Integral. */
933 bool isIntegral() const {
934 for(iterator i = begin(), e=end(); i!=e; ++i){
935 if(!(*i).isIntegral()){
936 return false;
937 }
938 }
939 return true;
940 }
941
942 static Polynomial sumPolynomials(const std::vector<Polynomial>& polynomials);
943
944 /** Returns true if the polynomial contains a non-linear monomial.*/
945 bool isNonlinear() const;
946
947 /** Check whether this polynomial is only a single variable. */
948 bool isVariable() const
949 {
950 return singleton() && getHead().getVarList().singleton()
951 && getHead().coefficientIsOne();
952 }
953 /** Return the variable, given that isVariable() holds. */
954 Variable getVariable() const
955 {
956 Assert(isVariable());
957 return getHead().getVarList().getHead();
958 }
959
960 /**
961 * Selects a minimal monomial in the polynomial by the absolute value of
962 * the coefficient.
963 */
964 Monomial selectAbsMinimum() const;
965
966 /** Returns true if the absolute value of the head coefficient is one. */
967 bool leadingCoefficientIsAbsOne() const;
968 bool leadingCoefficientIsPositive() const;
969 bool denominatorLCMIsOne() const;
970 bool numeratorGCDIsOne() const;
971
972 bool signNormalizedReducedSum() const {
973 return leadingCoefficientIsPositive() && denominatorLCMIsOne() && numeratorGCDIsOne();
974 }
975
976 /**
977 * Returns the Least Common Multiple of the denominators of the coefficients
978 * of the monomials.
979 */
980 Integer denominatorLCM() const;
981
982 /**
983 * Returns the GCD of the numerators of the monomials.
984 * Requires this to be an isIntegral() polynomial.
985 */
986 Integer numeratorGCD() const;
987
988 /**
989 * Returns the GCD of the coefficients of the monomials.
990 * Requires this to be an isIntegral() polynomial.
991 */
992 Integer gcd() const;
993
994 /** z must divide all of the coefficients of the polynomial. */
995 Polynomial exactDivide(const Integer& z) const;
996
997 Polynomial operator+(const Polynomial& vl) const;
998 Polynomial operator-(const Polynomial& vl) const;
999 Polynomial operator-() const{
1000 return (*this) * Rational(-1);
1001 }
1002
1003 Polynomial operator*(const Rational& q) const;
1004 Polynomial operator*(const Constant& c) const;
1005 Polynomial operator*(const Monomial& mono) const;
1006
1007 Polynomial operator*(const Polynomial& poly) const;
1008
1009 /**
1010 * Viewing the integer polynomial as a list [(* coeff_i mono_i)]
1011 * The quotient and remainder of p divided by the non-zero integer z is:
1012 * q := [(* floor(coeff_i/z) mono_i )]
1013 * r := [(* rem(coeff_i/z) mono_i)]
1014 * computeQR(p,z) returns the node (+ q r).
1015 *
1016 * q and r are members of the Polynomial class.
1017 * For example:
1018 * computeQR( p = (+ 5 (* 3 x) (* 8 y)) , z = 2) returns
1019 * (+ (+ 2 x (* 4 y)) (+ 1 x))
1020 */
1021 static Node computeQR(const Polynomial& p, const Integer& z);
1022
1023 /** Returns the coefficient associated with the VarList in the polynomial. */
1024 Constant getCoefficient(const VarList& vl) const;
1025
1026 uint32_t maxLength() const{
1027 iterator i = begin(), e=end();
1028 if( i == e){
1029 return 1;
1030 }else{
1031 uint32_t max = (*i).coefficientLength();
1032 ++i;
1033 for(; i!=e; ++i){
1034 uint32_t curr = (*i).coefficientLength();
1035 if(curr > max){
1036 max = curr;
1037 }
1038 }
1039 return max;
1040 }
1041 }
1042
1043 uint32_t numMonomials() const {
1044 if( getNode().getKind() == kind::PLUS ){
1045 return getNode().getNumChildren();
1046 }else if(isZero()){
1047 return 0;
1048 }else{
1049 return 1;
1050 }
1051 }
1052
1053 const Rational& asConstant() const{
1054 Assert(isConstant());
1055 return getNode().getConst<Rational>();
1056 //return getHead().getConstant().getValue();
1057 }
1058
1059 bool isVarList() const {
1060 if(singleton()){
1061 return VarList::isMember(getNode());
1062 }else{
1063 return false;
1064 }
1065 }
1066
1067 VarList asVarList() const {
1068 Assert(isVarList());
1069 return getHead().getVarList();
1070 }
1071
1072 size_t getComplexity() const;
1073
1074 friend class SumPair;
1075 friend class Comparison;
1076
1077 /** Returns a node that if asserted ensures v is the abs of this polynomial.*/
1078 Node makeAbsCondition(Variable v){
1079 return makeAbsCondition(v, *this);
1080 }
1081
1082 /** Returns a node that if asserted ensures v is the abs of p.*/
1083 static Node makeAbsCondition(Variable v, Polynomial p);
1084
1085 };/* class Polynomial */
1086
1087
1088 /**
1089 * SumPair is a utility class that extends polynomials for use in computations.
1090 * A SumPair is always a combination of (+ p c) where
1091 * c is a constant and p is a polynomial such that p = 0 or !p.containsConstant().
1092 *
1093 * These are a useful utility for representing the equation p = c as (+ p -c) where the pair
1094 * is known to implicitly be equal to 0.
1095 *
1096 * SumPairs do not have unique representations due to the potential for p = 0.
1097 * This makes them inappropriate for normal forms.
1098 */
1099 class SumPair : public NodeWrapper {
1100 private:
1101 static Node toNode(const Polynomial& p, const Constant& c){
1102 return NodeManager::currentNM()->mkNode(kind::PLUS, p.getNode(), c.getNode());
1103 }
1104
1105 SumPair(TNode n) : NodeWrapper(n) { Assert(isNormalForm()); }
1106
1107 public:
1108 SumPair(const Polynomial& p):
1109 NodeWrapper(toNode(p, Constant::mkConstant(0)))
1110 {
1111 Assert(isNormalForm());
1112 }
1113
1114 SumPair(const Polynomial& p, const Constant& c):
1115 NodeWrapper(toNode(p, c))
1116 {
1117 Assert(isNormalForm());
1118 }
1119
1120 static bool isMember(TNode n) {
1121 if(n.getKind() == kind::PLUS && n.getNumChildren() == 2){
1122 if(Constant::isMember(n[1])){
1123 if(Polynomial::isMember(n[0])){
1124 Polynomial p = Polynomial::parsePolynomial(n[0]);
1125 return p.isZero() || (!p.containsConstant());
1126 }else{
1127 return false;
1128 }
1129 }else{
1130 return false;
1131 }
1132 }else{
1133 return false;
1134 }
1135 }
1136
1137 bool isNormalForm() const {
1138 return isMember(getNode());
1139 }
1140
1141 Polynomial getPolynomial() const {
1142 return Polynomial::parsePolynomial(getNode()[0]);
1143 }
1144
1145 Constant getConstant() const {
1146 return Constant::mkConstant((getNode())[1]);
1147 }
1148
1149 SumPair operator+(const SumPair& other) const {
1150 return SumPair(getPolynomial() + other.getPolynomial(),
1151 getConstant() + other.getConstant());
1152 }
1153
1154 SumPair operator*(const Constant& c) const {
1155 return SumPair(getPolynomial() * c, getConstant() * c);
1156 }
1157
1158 SumPair operator-(const SumPair& other) const {
1159 return (*this) + (other * Constant::mkConstant(-1));
1160 }
1161
1162 static SumPair mkSumPair(const Polynomial& p);
1163
1164 static SumPair mkSumPair(const Variable& var){
1165 return SumPair(Polynomial::mkPolynomial(var));
1166 }
1167
1168 static SumPair parseSumPair(TNode n){
1169 return SumPair(n);
1170 }
1171
1172 bool isIntegral() const{
1173 return getConstant().isIntegral() && getPolynomial().isIntegral();
1174 }
1175
1176 bool isConstant() const {
1177 return getPolynomial().isZero();
1178 }
1179
1180 bool isZero() const {
1181 return getConstant().isZero() && isConstant();
1182 }
1183
1184 uint32_t size() const{
1185 return getPolynomial().size();
1186 }
1187
1188 bool isNonlinear() const{
1189 return getPolynomial().isNonlinear();
1190 }
1191
1192 /**
1193 * Returns the greatest common divisor of gcd(getPolynomial()) and getConstant().
1194 * The SumPair must be integral.
1195 */
1196 Integer gcd() const {
1197 Assert(isIntegral());
1198 return (getPolynomial().gcd()).gcd(getConstant().getValue().getNumerator());
1199 }
1200
1201 uint32_t maxLength() const {
1202 Assert(isIntegral());
1203 return std::max(getPolynomial().maxLength(), getConstant().length());
1204 }
1205
1206 static SumPair mkZero() {
1207 return SumPair(Polynomial::mkZero(), Constant::mkConstant(0));
1208 }
1209
1210 static Node computeQR(const SumPair& sp, const Integer& div);
1211
1212 };/* class SumPair */
1213
1214 /* class OrderedPolynomialPair { */
1215 /* private: */
1216 /* Polynomial d_first; */
1217 /* Polynomial d_second; */
1218 /* public: */
1219 /* OrderedPolynomialPair(const Polynomial& f, const Polynomial& s) */
1220 /* : d_first(f), */
1221 /* d_second(s) */
1222 /* {} */
1223
1224 /* /\** Returns the first part of the pair. *\/ */
1225 /* const Polynomial& getFirst() const { */
1226 /* return d_first; */
1227 /* } */
1228
1229 /* /\** Returns the second part of the pair. *\/ */
1230 /* const Polynomial& getSecond() const { */
1231 /* return d_second; */
1232 /* } */
1233
1234 /* OrderedPolynomialPair operator*(const Constant& c) const; */
1235 /* OrderedPolynomialPair operator+(const Polynomial& p) const; */
1236
1237 /* /\** Returns true if both of the polynomials are constant. *\/ */
1238 /* bool isConstant() const; */
1239
1240 /* /\** */
1241 /* * Evaluates an isConstant() ordered pair as if */
1242 /* * (k getFirst() getRight()) */
1243 /* *\/ */
1244 /* bool evaluateConstant(Kind k) const; */
1245
1246 /* /\** */
1247 /* * Returns the Least Common Multiple of the monomials */
1248 /* * on the lefthand side and the constant on the right. */
1249 /* *\/ */
1250 /* Integer denominatorLCM() const; */
1251
1252 /* /\** Constructs a SumPair. *\/ */
1253 /* SumPair toSumPair() const; */
1254
1255
1256 /* OrderedPolynomialPair divideByGCD() const; */
1257 /* OrderedPolynomialPair multiplyConstant(const Constant& c) const; */
1258
1259 /* /\** */
1260 /* * Returns true if all of the variables are integers, */
1261 /* * and the coefficients are integers. */
1262 /* *\/ */
1263 /* bool isIntegral() const; */
1264
1265 /* /\** Returns true if all of the variables are integers. *\/ */
1266 /* bool allIntegralVariables() const { */
1267 /* return getFirst().allIntegralVariables() && getSecond().allIntegralVariables(); */
1268 /* } */
1269 /* }; */
1270
1271 class Comparison : public NodeWrapper {
1272 private:
1273
1274 static Node toNode(Kind k, const Polynomial& l, const Constant& c);
1275 static Node toNode(Kind k, const Polynomial& l, const Polynomial& r);
1276
1277 Comparison(TNode n);
1278
1279 /**
1280 * Creates a node in normal form equivalent to (= l 0).
1281 * All variables in l are integral.
1282 */
1283 static Node mkIntEquality(const Polynomial& l);
1284
1285 /**
1286 * Creates a comparison equivalent to (k l 0).
1287 * k is either GT or GEQ.
1288 * All variables in l are integral.
1289 */
1290 static Node mkIntInequality(Kind k, const Polynomial& l);
1291
1292 /**
1293 * Creates a node equivalent to (= l 0).
1294 * It is not the case that all variables in l are integral.
1295 */
1296 static Node mkRatEquality(const Polynomial& l);
1297
1298 /**
1299 * Creates a comparison equivalent to (k l 0).
1300 * k is either GT or GEQ.
1301 * It is not the case that all variables in l are integral.
1302 */
1303 static Node mkRatInequality(Kind k, const Polynomial& l);
1304
1305 public:
1306
1307 Comparison(bool val) :
1308 NodeWrapper(NodeManager::currentNM()->mkConst(val))
1309 { }
1310
1311 /**
1312 * Given a literal to TheoryArith return a single kind to
1313 * to indicate its underlying structure.
1314 * The function returns the following in each case:
1315 * - (K left right) -> K where is either EQUAL, GT, or GEQ
1316 * - (CONST_BOOLEAN b) -> CONST_BOOLEAN
1317 * - (NOT (EQUAL left right)) -> DISTINCT
1318 * - (NOT (GT left right)) -> LEQ
1319 * - (NOT (GEQ left right)) -> LT
1320 * If none of these match, it returns UNDEFINED_KIND.
1321 */
1322 static Kind comparisonKind(TNode literal);
1323
1324 Kind comparisonKind() const { return comparisonKind(getNode()); }
1325
1326 static Comparison mkComparison(Kind k, const Polynomial& l, const Polynomial& r);
1327
1328 /** Returns true if the comparison is a boolean constant. */
1329 bool isBoolean() const;
1330
1331 /**
1332 * Returns true if the comparison is either a boolean term,
1333 * in integer normal form or mixed normal form.
1334 */
1335 bool isNormalForm() const;
1336
1337 private:
1338 bool isNormalGT() const;
1339 bool isNormalGEQ() const;
1340
1341 bool isNormalLT() const;
1342 bool isNormalLEQ() const;
1343
1344 bool isNormalEquality() const;
1345 bool isNormalDistinct() const;
1346 bool isNormalEqualityOrDisequality() const;
1347
1348 bool allIntegralVariables() const {
1349 return getLeft().allIntegralVariables() && getRight().allIntegralVariables();
1350 }
1351 bool rightIsConstant() const;
1352
1353 public:
1354 Polynomial getLeft() const;
1355 Polynomial getRight() const;
1356
1357 /* /\** Normal form check if at least one variable is real. *\/ */
1358 /* bool isMixedCompareNormalForm() const; */
1359
1360 /* /\** Normal form check if at least one variable is real. *\/ */
1361 /* bool isMixedEqualsNormalForm() const; */
1362
1363 /* /\** Normal form check is all variables are integer.*\/ */
1364 /* bool isIntegerCompareNormalForm() const; */
1365
1366 /* /\** Normal form check is all variables are integer.*\/ */
1367 /* bool isIntegerEqualsNormalForm() const; */
1368
1369
1370 /**
1371 * Returns true if all of the variables are integers, the coefficients are integers,
1372 * and the right hand coefficient is an integer.
1373 */
1374 bool debugIsIntegral() const;
1375
1376 static Comparison parseNormalForm(TNode n);
1377
1378 inline static bool isNormalAtom(TNode n){
1379 Comparison parse = Comparison::parseNormalForm(n);
1380 return parse.isNormalForm();
1381 }
1382
1383 size_t getComplexity() const;
1384
1385 SumPair toSumPair() const;
1386
1387 Polynomial normalizedVariablePart() const;
1388 DeltaRational normalizedDeltaRational() const;
1389
1390 /**
1391 * Transforms a Comparison object into a stronger normal form:
1392 * Polynomial ~Kind~ Constant
1393 *
1394 * From the comparison, this method resolved a negation (if present) and
1395 * moves everything to the left side.
1396 * If split_constant is false, the constant is always zero.
1397 * If split_constant is true, the polynomial has no constant term and is
1398 * normalized to have leading coefficient one.
1399 */
1400 std::tuple<Polynomial, Kind, Constant> decompose(
1401 bool split_constant = false) const;
1402
1403 };/* class Comparison */
1404
1405 } // namespace arith
1406 } // namespace theory
1407 } // namespace CVC5
1408
1409 #endif /* CVC4__THEORY__ARITH__NORMAL_FORM_H */