-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathLASolver.cc
More file actions
1065 lines (920 loc) · 33.5 KB
/
LASolver.cc
File metadata and controls
1065 lines (920 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2019-2022, Antti Hyvarinen <antti.hyvarinen@gmail.com>
* Copyright (c) 2019-2022, Martin Blicha <martin.blicha@gmail.com>
*
* SPDX-License-Identifier: MIT
*/
#include "LASolver.h"
#include "FarkasInterpolator.h"
#include "LA.h"
#include "ModelBuilder.h"
#include "LIAInterpolator.h"
#include "CutCreator.h"
#include <unordered_set>
static SolverDescr descr_la_solver("LA Solver", "Solver for Quantifier Free Linear Arithmetics");
PtAsgn LASolver::getAsgnByBound(LABoundRef br) const {
return LABoundRefToLeqAsgn[boundStore[br].getId()];
}
LABoundStore::BoundInfo LASolver::addBound(PTRef leq_tr) {
auto [const_tr, sum_tr] = logic.leqToConstantAndTerm(leq_tr);
assert(logic.isNumConst(const_tr) && logic.isLinearTerm(sum_tr));
bool sum_term_is_negated = laVarMapper.isNegated(sum_tr);
LVRef v = laVarMapper.getVarByLeqId(logic.getPterm(leq_tr).getId());
assert(v == laVarMapper.getVarByPTId(logic.getPterm(sum_tr).getId()));
LABoundStore::BoundInfo bi;
LABoundRef br_pos;
LABoundRef br_neg;
if (sum_term_is_negated) {
opensmt::Real constr_neg = -logic.getNumConst(const_tr);
bi = boundStore.allocBoundPair(v, this->getBoundsValue(v, constr_neg, false));
br_pos = bi.ub;
br_neg = bi.lb;
}
else {
const Real& constr = logic.getNumConst(const_tr);
bi = boundStore.allocBoundPair(v, this->getBoundsValue(v, constr, true));
br_pos = bi.lb;
br_neg = bi.ub;
}
int br_pos_idx = boundStore[br_pos].getId();
int br_neg_idx = boundStore[br_neg].getId();
int tid = Idx(logic.getPterm(leq_tr).getId());
if (LeqToLABoundRefPair.size() <= tid) {
LeqToLABoundRefPair.growTo(tid + 1);
}
LeqToLABoundRefPair[tid] = LABoundRefPair{br_pos, br_neg};
if (LABoundRefToLeqAsgn.size() <= std::max(br_pos_idx, br_neg_idx)) {
LABoundRefToLeqAsgn.growTo(std::max(br_pos_idx, br_neg_idx) + 1);
}
LABoundRefToLeqAsgn[br_pos_idx] = PtAsgn(leq_tr, l_True);
LABoundRefToLeqAsgn[br_neg_idx] = PtAsgn(leq_tr, l_False);
return bi;
}
void LASolver::updateBound(PTRef tr)
{
// If the bound already exists, do nothing.
int id = Idx(logic.getPterm(tr).getId());
if ((LeqToLABoundRefPair.size() > id) &&
!(LeqToLABoundRefPair[id] == LABoundRefPair{LABoundRef_Undef, LABoundRef_Undef})) {
return;
}
LABoundStore::BoundInfo bi = addBound(tr);
boundStore.updateBound(bi);
}
bool LASolver::isValid(PTRef tr)
{
return logic.isLeq(tr); // MB: LA solver expects only inequalities in LEQ form!
}
void LASolver::isProperLeq(PTRef tr)
{
assert(logic.isAtom(tr));
assert(logic.isLeq(tr));
auto [cons, sum] = logic.leqToConstantAndTerm(tr);
assert(logic.isConstant(cons));
assert(logic.isNumVarOrIte(sum) || logic.isPlus(sum) || logic.isTimes(sum));
assert(!logic.isTimes(sum) || ((logic.isNumVarOrIte(logic.getPterm(sum)[0]) && logic.isOne(logic.mkNeg(logic.getPterm(sum)[1]))) ||
(logic.isNumVarOrIte(logic.getPterm(sum)[1]) && logic.isOne(logic.mkNeg(logic.getPterm(sum)[0])))));
(void) cons; (void)sum;
}
LASolver::LASolver(SMTConfig & c, ArithLogic & l) : LASolver(descr_la_solver, c, l) {}
LASolver::LASolver(SolverDescr dls, SMTConfig & c, ArithLogic & l)
: TSolver((SolverId) dls, (const char *) dls, c)
, logic(l)
, laVarMapper(l)
, boundStore(laVarStore)
, simplex(boundStore)
{
dec_limit.push(0);
status = INIT;
}
int LASolver::backtrackLevel() {
return dec_limit.size() - 1;
}
void LASolver::pushDecision(PtAsgn asgn)
{
int_decisions.push({asgn, backtrackLevel()});
decision_trace.push(asgn);
}
void LASolver::clearSolver()
{
status = INIT;
simplex.clear();
decision_trace.clear();
int_decisions.clear();
dec_limit.clear();
TSolver::clearSolver();
laVarStore.clear();
laVarMapper.clear();
boundStore.clear();
LABoundRefToLeqAsgn.clear();
LeqToLABoundRefPair.clear();
int_vars.clear();
int_vars_map.clear();
// TODO: clear statistics
// this->egraphStats.clear();
}
void LASolver::storeExplanation(Simplex::Explanation &&explanationBounds) {
explanation.clear();
explanationCoefficients.clear();
for (std::size_t i = 0; i < explanationBounds.size(); i++) {
PtAsgn asgn = getAsgnByBound(explanationBounds[i].boundref);
explanation.push(asgn);
explanationCoefficients.push_back(explanationBounds[i].coeff);
}
}
bool LASolver::check_simplex(bool complete) {
// opensmt::StopWatch check_timer(egraphStats.simplex_timer);
// printf(" - check %d\n", debug_check_count++);
(void)complete;
// check if we stop reading constraints
if (status == INIT) {
initSolver();
}
storeExplanation(simplex.checkSimplex());
if (explanation.size() == 0)
setStatus(SAT);
else {
setStatus(UNSAT);
}
getStatus() ? generalTSolverStats.sat_calls ++ : generalTSolverStats.unsat_calls ++;
// printf(" - check ended\n");
// printf(" => %s\n", getStatus() ? "sat" : "unsat");
// if (getStatus())
// model.printModelState();
return getStatus();
}
//
// The model system
//
/*
bool LASolver::isModelOutOfBounds(LVRef v) const {
return simplex.isModelOutOfBounds(v);
}
bool LASolver::isModelOutOfUpperBound(LVRef v) const
{
return simplex.isModelOutOfBounds(v);
}
bool LASolver::isModelOutOfLowerBound(LVRef v) const
{
return ( model.read(v) < model.Lb(v) );
}
const Delta LASolver::overBound(LVRef v) const
{
assert( isModelOutOfBounds(v) );
if (isModelOutOfUpperBound(v))
{
return ( Delta(model.read(v) - model.Ub(v)) );
}
else if ( isModelOutOfLowerBound(v) )
{
return ( Delta(model.Lb(v) - model.read(v)) );
}
assert (false);
printf("Problem in overBound, LRASolver.C:%d\n", __LINE__);
exit(1);
}
*/
void LASolver::setBound(PTRef leq_tr)
{
// printf("Setting bound for %s\n", logic.printTerm(leq_tr));
addBound(leq_tr);
}
opensmt::Number LASolver::getNum(PTRef r) {
return logic.getNumConst(r);
}
void LASolver::notifyVar(LVRef v) {
assert(logic.isNumVarOrIte(getVarPTRef(v)));
if (logic.yieldsSortInt(getVarPTRef(v))) {
markVarAsInt(v);
}
}
void LASolver::markVarAsInt(LVRef v) {
if (!int_vars_map.has(v)) {
int_vars_map.insert(v, true);
int_vars.push(v);
}
}
bool LASolver::hasVar(PTRef expr) {
expr = laVarMapper.isNegated(expr) ? logic.mkNeg(expr) : expr;
PTId id = logic.getPterm(expr).getId();
return laVarMapper.hasVar(id);
}
LVRef LASolver::getLAVar_single(PTRef expr_in) {
assert(logic.isLinearTerm(expr_in));
PTId id = logic.getPterm(expr_in).getId();
if (laVarMapper.hasVar(id)) {
return getVarForTerm(expr_in);
}
PTRef expr = laVarMapper.isNegated(expr_in) ? logic.mkNeg(expr_in) : expr_in;
LVRef x = laVarStore.getNewVar();
laVarMapper.registerNewMapping(x, expr);
return x;
}
std::unique_ptr<Tableau::Polynomial> LASolver::expressionToLVarPoly(PTRef term) {
auto poly = std::make_unique<Tableau::Polynomial>();
bool negated = laVarMapper.isNegated(term);
for (int i = 0; i < logic.getPterm(term).size(); i++) {
auto [v,c] = logic.splitTermToVarAndConst(logic.getPterm(term)[i]);
LVRef var = getLAVar_single(v);
Real coeff = getNum(c);
if (negated) {
coeff.negate();
}
poly->addTerm(var, std::move(coeff));
}
return poly;
}
//
// Get a possibly new LAVar for a PTRef term. We may assume that the term is of one of the following forms,
// where x is a real variable or ite, and p_i are products of a real variable or ite and a real constant
//
// (1) x
// (2a) (* x -1)
// (2b) (* -1 x)
// (3) x + p_1 + ... + p_n
// (4a) (* x -1) + p_1 + ... + p_n
// (4b) (* -1 x) + p_1 + ... + p_n
//
LVRef LASolver::exprToLVar(PTRef expr) {
LVRef x = LVRef::Undef;
if (laVarMapper.hasVar(expr)){
x = getVarForTerm(expr);
if (simplex.isProcessedByTableau(x)){
return x;
}
}
if (logic.isNumVarOrIte(expr) || logic.isTimes(expr)) {
// Case (1), (2a), and (2b)
auto [v,c] = logic.splitTermToVarAndConst(expr);
assert(logic.isNumVarOrIte(v) || (laVarMapper.isNegated(v) && logic.isNumVarOrIte(logic.mkNeg(v))));
x = getLAVar_single(v);
simplex.newNonbasicVar(x);
notifyVar(x);
}
else {
// Cases (3), (4a) and (4b)
x = getLAVar_single(expr);
auto poly = expressionToLVarPoly(expr);
// ensure the simplex knows about all the variables
// and compute if this poly is always integer
bool isInt = true;
for (auto const & term : *poly) {
notifyVar(term.var);
simplex.nonbasicVar(term.var);
// MB: Notify must be called before the query isIntVar!
isInt &= isIntVar(term.var) && term.coeff.isInteger();
}
simplex.newRow(x, std::move(poly));
if (isInt) {
markVarAsInt(x);
}
}
assert(x != LVRef::Undef);
return x;
}
//
// Reads the constraint into the solver
//
void LASolver::declareAtom(PTRef leq_tr)
{
if (!logic.isLeq(leq_tr)) { return; }
if (isInformed(leq_tr)) { return; }
setInformed(leq_tr);
if (status != INIT)
{
// Treat the PTRef as it is pushed on-the-fly
// status = INCREMENT;
assert( status == SAT );
PTRef term = logic.getPterm(leq_tr)[1];
LVRef v = exprToLVar(term);
laVarMapper.addLeqVar(leq_tr, v);
updateBound(leq_tr);
}
// DEBUG check
isProperLeq(leq_tr);
setKnown(leq_tr);
}
LVRef LASolver::splitOnMostInfeasible(vec<LVRef> const & varsToFix) const {
opensmt::Real maxDistance = 0;
LVRef chosen = LVRef::Undef;
for (LVRef x : varsToFix) {
Delta val = simplex.getValuation(x);
assert(not val.hasDelta());
assert(not val.R().isInteger());
opensmt::Real distance = std::min(val.R().ceil() - val.R(), val.R() - val.R().floor());
if (distance > maxDistance) {
maxDistance = std::move(distance);
chosen = x;
}
}
return chosen;
}
TRes LASolver::checkIntegersAndSplit() {
vec<LVRef> varsToFix;
varsToFix.capacity(int_vars.size());
for (LVRef x : int_vars) {
if (not isModelInteger(x)) {
assert(not simplex.hasLBound(x) or not simplex.hasUBound(x) or simplex.Ub(x) - simplex.Lb(x) >= 1);
varsToFix.push(x);
}
}
if (varsToFix.size() == 0) {
setStatus(SAT);
return TRes::SAT;
}
if (shouldTryCutFromProof()) {
auto res = cutFromProof();
if (res != TRes::UNKNOWN) {
return res;
}
}
LVRef chosen = splitOnMostInfeasible(varsToFix);
assert(chosen != LVRef::Undef);
auto splitLowerVal = simplex.getValuation(chosen).R().floor();
//x <= c || x >= c+1;
PTRef varPTRef = getVarPTRef(chosen);
PTRef upperBound = logic.mkLeq(varPTRef, logic.mkIntConst(splitLowerVal));
PTRef lowerBound = logic.mkGeq(varPTRef, logic.mkIntConst(splitLowerVal + 1));
PTRef constr = logic.mkOr(upperBound, lowerBound);
splitondemand.push(constr);
setStatus(NEWSPLIT);
return TRes::SAT;
}
void LASolver::getNewSplits(vec<PTRef>& splits) {
splitondemand.copyTo(splits);
splitondemand.clear();
setStatus(SAT);
}
//
// Push the constraint into the solver and increase the level
//
bool LASolver::assertLit(PtAsgn asgn)
{
assert(asgn.sgn != l_Undef);
// printf("Assert %d\n", debug_assert_count++);
// Special cases of the "inequalitites"
if (logic.isTrue(asgn.tr) && asgn.sgn == l_True) {
generalTSolverStats.sat_calls ++;
return true;
}
if (logic.isFalse(asgn.tr) && asgn.sgn == l_False) {
generalTSolverStats.sat_calls ++;
return true;
}
if (logic.isTrue(asgn.tr) && asgn.sgn == l_False) {
generalTSolverStats.unsat_calls ++;
return false;
}
if (logic.isFalse(asgn.tr) && asgn.sgn == l_True) {
generalTSolverStats.unsat_calls ++;
return false;
}
// check if we stop reading constraints
if( status == INIT )
initSolver( );
if (hasPolarity(asgn.tr) && getPolarity(asgn.tr) == asgn.sgn) {
// already known, no new information
// MB: The deductions done by this TSolver are also marked using polarity.
// The invariant is that TSolver will not process the literal again (when asserted from the SAT solver)
// once it is marked for deduction, so the implementation must count with that.
assert(getStatus());
generalTSolverStats.sat_calls ++;
return getStatus();
}
LABoundRefPair p = getBoundRefPair(asgn.tr);
LABoundRef bound_ref = asgn.sgn == l_False ? p.neg : p.pos;
// printf("Model state\n");
// model.printModelState();
// printf("Asserting %s (%d)\n", boundStore.printBound(bound_ref), asgn.tr.x);
// printf(" - equal to %s%s\n", asgn.sgn == l_True ? "" : "not ", logic.pp(asgn.tr));
LVRef it = getVarForLeq(asgn.tr);
// Constraint to push was not found in local storage. Most likely it was not read properly before
assert(it != LVRef::Undef);
if (assertBoundOnVar( it, bound_ref))
{
assert(getStatus());
setPolarity(asgn.tr, asgn.sgn);
pushDecision(asgn);
getSimpleDeductions(it, bound_ref);
generalTSolverStats.sat_calls++;
} else {
generalTSolverStats.unsat_calls++;
}
return getStatus();
}
bool LASolver::assertBoundOnVar(LVRef it, LABoundRef itBound_ref) {
// No check whether the bounds are consistent for the polynomials. This is done later with Simplex.
assert(status == SAT);
assert(it != LVRef::Undef);
storeExplanation(simplex.assertBoundOnVar(it, itBound_ref));
if (explanation.size() > 0) {
return setStatus(UNSAT);
}
return getStatus();
}
//
// Push the solver one level down
//
void LASolver::pushBacktrackPoint( )
{
// Check if any updates need to be repeated after backtrack
simplex.pushBacktrackPoint();
dec_limit.push(decision_trace.size());
// Update the generic deductions state
TSolver::pushBacktrackPoint();
}
PtAsgn
LASolver::popDecisions()
{
PtAsgn popd = PtAsgn_Undef;
assert(decision_trace.size() - dec_limit.last() == 1 || decision_trace.size() - dec_limit.last() == 0);
if (decision_trace.size() - dec_limit.last() == 1) {
popd = int_decisions.last().asgn;
int_decisions.pop();
}
decision_trace.shrink(decision_trace.size() - dec_limit.last());
return popd;
}
PtAsgn LASolver::popTermBacktrackPoint() {
simplex.popBacktrackPoint();
PtAsgn popd = popDecisions();
dec_limit.pop();
return popd;
}
// Pop the solver one level up
// NOTE: this method should not be used, pop multiple points is more efficient with popBacktrackPoints rather than popping one by one
void LASolver::popBacktrackPoint( ) {
this->popBacktrackPoints(1);
}
// Pop the solver given number of times
//
void LASolver::popBacktrackPoints(unsigned int count) {
for ( ; count > 0; --count){
PtAsgn dec = popTermBacktrackPoint();
if (dec != PtAsgn_Undef) {
clearPolarity(dec.tr);
LVRef it = getVarForLeq(dec.tr);
simplex.boundDeactivated(it);
}
TSolver::popBacktrackPoint();
}
simplex.finalizeBacktracking();
setStatus(SAT);
}
void LASolver::initSolver()
{
if (status == INIT)
{
#ifdef GAUSSIAN_DEBUG
cout << "Columns:" << '\n';
for (int i = 0; i < columns.size(); i++)
cout << columns[i] << '\n';
cout << "Rows:" << '\n';
for (int i = 0; i < rows.size(); i++)
cout << rows[i] << '\n';
#endif
const auto & known_PTRefs = getInformed();
for(PTRef leq_tr : known_PTRefs) {
Pterm const & leq_t = logic.getPterm(leq_tr);
// Terms are of form c <= t where
// - c is a constant and
// - t is either a variable or a sum
// leq_t[0] is const and leq_t[1] is term
PTRef term = leq_t[1];
// Ensure that all variables exists, build the polynomial, and update the occurrences.
LVRef v = exprToLVar(term);
laVarMapper.addLeqVar(leq_tr, v);
// Assumes that the LRA variable has been already declared
setBound(leq_tr);
}
boundStore.buildBounds(); // Bounds are needed for gaussian elimination
simplex.initModel();
status = SAT;
}
else {
throw OsmtInternalException("Solver can not be initialized in the state different from INIT");
}
}
//
// Returns boolean value correspondent to the current solver status
//
inline bool LASolver::getStatus( )
{
switch( status ) {
case SAT:
{
return true;
break;
}
case UNSAT:
{
return false;
break;
}
case NEWSPLIT:
{
return true;
break;
}
case UNKNOWN:
// cerr << "LA Solver status is unknown" << endl;
status = SAT;
return true;
case INIT:
case ERROR:
default:
throw OsmtApiException("Status is undef!");
}
}
//
// Sets the new solver status and returns the correspondent lbool value
//
bool LASolver::setStatus( LASolverStatus s )
{
status = s;
if (s == UNSAT)
has_explanation = true;
return getStatus( );
}
void LASolver::getSimpleDeductions(LVRef v, LABoundRef br)
{
// printf("Deducing from bound %s\n", boundStore.printBound(br));
// printf("The full bound list for %s:\n%s\n", logic.printTerm(lva[v].getPTRef()), boundStore.printBounds(v));
const LABound& bound = boundStore[br];
if (bound.getType() == bound_l) {
for (int it = bound.getIdx().x - 1; it >= 0; it = it - 1) {
LABoundRef bound_prop_ref = boundStore.getBoundByIdx(v, it);
LABound &bound_prop = boundStore[bound_prop_ref];
if (bound_prop.getType() != bound_l)
continue;
deduce(bound_prop_ref);
}
} else if (bound.getType() == bound_u) {
for (int it = bound.getIdx().x + 1; it < boundStore.getBounds(v).size() - 1; it = it + 1) {
LABoundRef bound_prop_ref = boundStore.getBoundByIdx(v, it);
LABound & bound_prop = boundStore[bound_prop_ref];
if (bound_prop.getType() != bound_u)
continue;
deduce(bound_prop_ref);
}
}
}
void LASolver::deduce(LABoundRef bound_prop) {
PtAsgn ba = getAsgnByBound(bound_prop);
if (!hasPolarity(ba.tr)) {
storeDeduction(PtAsgn_reason(ba.tr, ba.sgn, PTRef_Undef));
}
}
void LASolver::getConflict(vec<PtAsgn> & conflict) {
for (PtAsgn lit : explanation) {
conflict.push(lit);
}
}
// We may assume that the term is of the following forms
// (1) (* x c)
// (2) (* c x)
// (3) c
opensmt::Number LASolver::evaluateTerm(PTRef tr)
{
opensmt::Real val(0);
// Case (3)
if (logic.isNumConst(tr))
return logic.getNumConst(tr);
// Cases (1) & (2)
auto [var, coeff] = logic.splitTermToVarAndConst(tr);
if (!hasVar(var)) {
// MB: This variable is not known to the LASolver. Most probably it was not part of the query.
// We can assign it any value.
return 0;
}
val += logic.getNumConst(coeff) * concrete_model[getVarId(getVarForTerm(var))];
return val;
}
void LASolver::fillTheoryFunctions(ModelBuilder & modelBuilder) const {
for (LVRef lvar : laVarStore) {
PTRef term = laVarMapper.getVarPTRef(lvar);
if (logic.isNumVar(term)) {
PTRef val = logic.mkConst(logic.getSortRef(term), concrete_model[getVarId(lvar)]);
modelBuilder.addVarValue(term, val);
}
}
}
void LASolver::computeConcreteModel(LVRef v, const opensmt::Real& delta) {
while (concrete_model.size() <= getVarId(v))
concrete_model.push_back(0);
Delta val = simplex.getValuation(v);
concrete_model[getVarId(v)] = val.R() + val.D() * delta;
}
//
// Detect the appropriate value for symbolic delta and stores the model
//
void LASolver::computeModel()
{
assert( status == SAT );
opensmt::Real delta = simplex.computeDelta();
for (LVRef var : laVarStore)
{
computeConcreteModel(var, delta);
}
}
LASolver::~LASolver( )
{
#ifdef STATISTICS
printStatistics(std::cerr);
#endif // STATISTICS
}
ArithLogic& LASolver::getLogic() { return logic; }
/**
* Given an inequality v ~ c (with ~ is either < or <=), compute the correct bounds on the variable.
* The correct values of the bounds are computed differently, based on whether the value of v must be Int or not.
*
* @param c Real number representing the upper bound
* @param strict inequality is LEQ if false, LT if true
* @return The values of upper and lower bound corresponding to the inequality
*/
LABoundStore::BoundValuePair LASolver::getBoundsValue(LVRef v, const Real & c, bool strict) {
return isIntVar(v) ? getBoundsValueForIntVar(c, strict) : getBoundsValueForRealVar(c, strict);
}
/**
* Given an imaginary inequality v ~ c (with ~ is either < or <=), compute the interger bounds on the variable
*
* @param c Real number representing the upper bound
* @param strict inequality is LEQ if false, LT if true
* @return The integer values of upper and lower bound corresponding to the inequality
*/
LABoundStore::BoundValuePair LASolver::getBoundsValueForIntVar(const Real & c, bool strict) {
if (strict) {
// v < c => UB is ceiling(c-1), LB is ceiling(c)
return {Delta((c-1).ceil()), Delta(c.ceil())};
}
else {
// v <= c => UB is floor(c), LB is floor(c+1)
return {Delta(c.floor()), Delta((c+1).floor())};
}
}
/**
* Given an imaginary inequality v ~ c (with ~ is either < or <=), compute the real bounds on the variable
*
* @param c Real number representing the upper bound
* @param strict inequality is LEQ if false, LT if true
* @return The real values of upper and lower bound corresponding to the inequality
*/
LABoundStore::BoundValuePair LASolver::getBoundsValueForRealVar(const Real & c, bool strict) {
if (strict) {
// v < c => UB is c-\delta, LB is c
return { Delta(c, -1), Delta(c) };
}
else {
// v <= c => UB is c, LB is c+\delta
return { Delta(c), Delta(c, 1) };
}
}
lbool LASolver::getPolaritySuggestion(PTRef ptref) const {
if (!this->isInformed(ptref)) { return l_Undef; }
LVRef var = this->getVarForLeq(ptref);
LABoundRefPair bounds = getBoundRefPair(ptref);
assert( bounds.pos != LABoundRef_Undef && bounds.neg != LABoundRef_Undef );
return simplex.getPolaritySuggestion(var, bounds.pos, bounds.neg);
}
TRes LASolver::check(bool complete) {
bool rval = check_simplex(complete);
if (complete && rval) {
return checkIntegersAndSplit();
}
return rval ? TRes::SAT : TRes::UNSAT;
}
bool LASolver::isModelInteger(LVRef v) const
{
Delta val = simplex.getValuation(v);
return !( val.hasDelta() || !val.R().isInteger() );
}
PTRef LASolver::interpolateUsingEngine(FarkasInterpolator & interpolator) const {
auto itpAlgorithm = config.getLRAInterpolationAlgorithm();
if (itpAlgorithm == itp_lra_alg_strong) { return interpolator.getFarkasInterpolant(); }
else if (itpAlgorithm == itp_lra_alg_weak) { return interpolator.getDualFarkasInterpolant(); }
else if (itpAlgorithm == itp_lra_alg_factor) { return interpolator.getFlexibleInterpolant(opensmt::Real(config.getLRAStrengthFactor())); }
else if (itpAlgorithm == itp_lra_alg_decomposing_strong) { return interpolator.getDecomposedInterpolant(); }
else if (itpAlgorithm == itp_lra_alg_decomposing_weak) { return interpolator.getDualDecomposedInterpolant(); }
else {
assert(false); // Incorrect value in config
return interpolator.getFarkasInterpolant();
}
}
//
// Compute interpolants for the conflict
//
PTRef
LASolver::getRealInterpolant( const ipartitions_t & mask , std::map<PTRef, icolor_t> *labels, PartitionManager &pmanager) {
assert(status == UNSAT);
vec<PtAsgn> explCopy;
explanation.copyTo(explCopy);
FarkasInterpolator interpolator(logic, std::move(explCopy), explanationCoefficients, labels ? *labels : std::map<PTRef, icolor_t>{},
std::make_unique<GlobalTermColorInfo>(pmanager, mask));
return interpolateUsingEngine(interpolator);
}
PTRef LASolver::getIntegerInterpolant(std::map<PTRef, icolor_t> const& labels) {
assert(status == UNSAT);
LIAInterpolator interpolator(logic, LAExplanations::getLIAExplanation(logic, explanation, explanationCoefficients, labels));
return interpolateUsingEngine(interpolator);
}
void LASolver::printStatistics(std::ostream & out) {
TSolver::printStatistics(out);
laSolverStats.printStatistics(out);
}
bool LASolver::shouldTryCutFromProof() const {
if (this->config.produce_inter()) { return false; }
static unsigned long counter = 0;
return ++counter % 10 == 0;
}
namespace {
struct DefiningConstraint {
PTRef lhs;
opensmt::Real rhs;
};
/*
* Translates the set of defining constraints (linear equalities) into a suitable inner representation:
* - A sparse matrix A of coefficients and constants b
* - a map from column indices to the corresponding variables x
* - The result is to be interpreted as the linear system Ax = b
*/
std::pair<SparseLinearSystem,std::vector<PTRef>> linearSystemFromConstraints(std::vector<DefiningConstraint> const & constraints, ArithLogic & logic) {
vec<PTRef> terms;
auto fillTerms = [&logic](PTRef poly, vec<PTRef> & terms) {// reduces linear polynomial to a vector of the polynomial's terms
terms.clear();
if (logic.isPlus(poly)) {
for (PTRef arg : logic.getPterm(poly)) {
terms.push(arg);
}
} else {
terms.push(poly);
}
};
std::unordered_map<PTRef, unsigned, PTRefHash> varIndices;
uint32_t columns = 0;
// First pass to assign indices and find out number of columns
for (auto const & defConstraint : constraints) {
PTRef poly = defConstraint.lhs;
fillTerms(poly, terms);
for (PTRef arg : terms) {
auto [var, constant] = logic.splitTermToVarAndConst(arg);
assert(var != PTRef_Undef);
if (varIndices.find(var) == varIndices.end()) {
varIndices.insert({var, columns++});
}
}
}
uint32_t rows = constraints.size();
SparseColMatrix matrixA(RowCount{rows}, ColumnCount{columns});
std::vector<FastRational> rhs(rows);
std::vector<SparseColMatrix::ColumnPolynomial> columnPolynomials(columns);
// Second pass to build the actual matrix
for (unsigned row = 0; row < constraints.size(); ++row) {
rhs[row] = constraints[row].rhs;
PTRef poly = constraints[row].lhs;
fillTerms(poly, terms);
for (PTRef arg : terms) {
auto [var, constant] = logic.splitTermToVarAndConst(arg);
auto col = varIndices[var];
columnPolynomials[col].addTerm(IndexType{row}, logic.getNumConst(constant));
}
}
for (uint32_t i = 0; i < columnPolynomials.size(); ++i) {
matrixA.setColumn(ColIndex{i}, std::move(columnPolynomials[i]));
}
// compute the inverse map from column indices to variables
std::vector<PTRef> columnMapping(matrixA.colCount(), PTRef_Undef);
for (auto [var, index] : varIndices) {
columnMapping[index] = var;
}
assert(matrixA.colCount() == columnMapping.size());
return {SparseLinearSystem{std::move(matrixA), std::move(rhs)}, std::move(columnMapping)};
}
PTRef getSumFromTermVec(SparseColMatrix::TermVec const & termVec, vec<PTRef> const & toVarMap, ArithLogic & logic) {
vec<PTRef> args;
for (auto const & term : termVec) {
IndexType var = term.first;
auto const & coeff = term.second;
args.push(logic.mkTimes(toVarMap[var.x], logic.mkIntConst(coeff)));
}
return logic.mkPlus(std::move(args));
}
PTRef cutToSplit(CutCreator::Cut && cut, std::vector<PTRef> const & toVarMap, ArithLogic & logic) {
auto const & termVec = cut.first;
auto const & rhs = cut.second;
if (termVec.empty()) {
return PTRef_Undef;
}
PTRef constraint = getSumFromTermVec(termVec, toVarMap, logic);
auto lowerBoundValue = rhs.ceil();
auto upperBoundValue = rhs.floor();
PTRef upperBound = logic.mkLeq(constraint, logic.mkIntConst(upperBoundValue));
PTRef lowerBound = logic.mkGeq(constraint, logic.mkIntConst(lowerBoundValue));
return logic.mkOr(upperBound, lowerBound);
}
}
TRes LASolver::cutFromProof() {
auto isOnLowerBound = [this](LVRef var) { return simplex.hasLBound(var) and not simplex.isModelStrictlyOverLowerBound(var); };
auto isOnUpperBound = [this](LVRef var) { return simplex.hasUBound(var) and not simplex.isModelStrictlyUnderUpperBound(var); };
// Step 1: Gather defining constraints
std::vector<DefiningConstraint> constraints;
for (LVRef var : int_vars) {
bool isOnLower = isOnLowerBound(var);
bool isOnUpper = isOnUpperBound(var);
if (not isOnLower and not isOnUpper) { continue; }
PTRef term = laVarMapper.getVarPTRef(var);
auto const & val = isOnLower ? simplex.Lb(var) : simplex.Ub(var);
assert(not val.hasDelta());
auto const & rhs = val.R();
assert(rhs.isInteger());
constraints.push_back(DefiningConstraint{term, rhs});
// std::cout << logic.pp(term) << " = " << rhs << std::endl;
}
auto getVarValue = [this](PTRef var) {
assert(this->logic.isVar(var));
LVRef lvar = this->laVarMapper.getVarByPTId(logic.getPterm(var).getId());
Delta val = this->simplex.getValuation(lvar);
assert(not val.hasDelta());
return val.R();
};
CutCreator cutCreator(getVarValue);
auto [system, toVarMap] = linearSystemFromConstraints(constraints, logic);
auto cut = cutCreator.makeCut(std::move(system), toVarMap);
PTRef split = cutToSplit(std::move(cut), toVarMap, logic);
if (split == PTRef_Undef) {
return TRes::UNKNOWN;
}
splitondemand.push(split);
setStatus(NEWSPLIT);
return TRes::SAT;
}
vec<PTRef> LASolver::collectEqualitiesFor(vec<PTRef> const & vars, std::unordered_set<PTRef, PTRefHash> const & knownEqualities) {
struct DeltaHash {
std::size_t operator()(Delta const & d) const {
FastRationalHash hasher;
return (hasher(d.R()) ^ hasher(d.D()));
}
};
vec<PTRef> equalities;
std::unordered_map<Delta, vec<PTRef>, DeltaHash> eqClasses;
for (PTRef var : vars) {