GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/theory/arith/theory_arith_private.cpp Lines: 1759 2965 59.3 %
Date: 2021-09-07 Branches: 3438 12520 27.5 %

Line Exec Source
1
/******************************************************************************
2
 * Top contributors (to current version):
3
 *   Tim King, Alex Ozdemir, Andrew Reynolds
4
 *
5
 * This file is part of the cvc5 project.
6
 *
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.
11
 * ****************************************************************************
12
 *
13
 * [[ Add one-line brief description here ]]
14
 *
15
 * [[ Add lengthier description here ]]
16
 * \todo document this file
17
 */
18
19
#include "theory/arith/theory_arith_private.h"
20
21
#include <map>
22
#include <optional>
23
#include <queue>
24
#include <vector>
25
26
#include "base/output.h"
27
#include "context/cdhashset.h"
28
#include "context/cdinsert_hashmap.h"
29
#include "context/cdlist.h"
30
#include "context/cdqueue.h"
31
#include "context/context.h"
32
#include "expr/kind.h"
33
#include "expr/metakind.h"
34
#include "expr/node.h"
35
#include "expr/node_algorithm.h"
36
#include "expr/node_builder.h"
37
#include "expr/skolem_manager.h"
38
#include "options/arith_options.h"
39
#include "options/base_options.h"
40
#include "preprocessing/util/ite_utilities.h"
41
#include "proof/proof_generator.h"
42
#include "proof/proof_node_manager.h"
43
#include "proof/proof_rule.h"
44
#include "smt/logic_exception.h"
45
#include "smt/smt_statistics_registry.h"
46
#include "smt_util/boolean_simplification.h"
47
#include "theory/arith/approx_simplex.h"
48
#include "theory/arith/arith_ite_utils.h"
49
#include "theory/arith/arith_rewriter.h"
50
#include "theory/arith/arith_static_learner.h"
51
#include "theory/arith/arith_utilities.h"
52
#include "theory/arith/arithvar.h"
53
#include "theory/arith/congruence_manager.h"
54
#include "theory/arith/constraint.h"
55
#include "theory/arith/cut_log.h"
56
#include "theory/arith/delta_rational.h"
57
#include "theory/arith/dio_solver.h"
58
#include "theory/arith/linear_equality.h"
59
#include "theory/arith/matrix.h"
60
#include "theory/arith/nl/nonlinear_extension.h"
61
#include "theory/arith/normal_form.h"
62
#include "theory/arith/partial_model.h"
63
#include "theory/arith/simplex.h"
64
#include "theory/arith/theory_arith.h"
65
#include "theory/ext_theory.h"
66
#include "theory/quantifiers/fmf/bounded_integers.h"
67
#include "theory/rewriter.h"
68
#include "theory/theory_model.h"
69
#include "theory/trust_substitutions.h"
70
#include "theory/valuation.h"
71
#include "util/dense_map.h"
72
#include "util/integer.h"
73
#include "util/random.h"
74
#include "util/rational.h"
75
#include "util/result.h"
76
#include "util/statistics_stats.h"
77
78
using namespace std;
79
using namespace cvc5::kind;
80
81
namespace cvc5 {
82
namespace theory {
83
namespace arith {
84
85
static Node toSumNode(const ArithVariables& vars, const DenseMap<Rational>& sum);
86
static bool complexityBelow(const DenseMap<Rational>& row, uint32_t cap);
87
88
9926
TheoryArithPrivate::TheoryArithPrivate(TheoryArith& containing,
89
                                       Env& env,
90
9926
                                       BranchAndBound& bab)
91
    : EnvObj(env),
92
      d_containing(containing),
93
      d_foundNl(false),
94
      d_rowTracking(),
95
      d_bab(bab),
96
9926
      d_pnm(d_env.isTheoryProofProducing() ? d_env.getProofNodeManager()
97
                                           : nullptr),
98
      d_checker(),
99
19852
      d_pfGen(new EagerProofGenerator(d_pnm, userContext())),
100
      d_constraintDatabase(context(),
101
9926
                           userContext(),
102
                           d_partialModel,
103
                           d_congruenceManager,
104
                           RaiseConflict(*this),
105
                           d_pfGen.get(),
106
                           d_pnm),
107
      d_qflraStatus(Result::SAT_UNKNOWN),
108
      d_unknownsInARow(0),
109
      d_hasDoneWorkSinceCut(false),
110
9926
      d_learner(userContext()),
111
      d_assertionsThatDoNotMatchTheirLiterals(context()),
112
      d_nextIntegerCheckVar(0),
113
      d_constantIntegerVariables(context()),
114
      d_diseqQueue(context(), false),
115
      d_currentPropagationList(),
116
      d_learnedBounds(context()),
117
      d_preregisteredNodes(context()),
118
19852
      d_partialModel(context(), DeltaComputeCallback(*this)),
119
      d_errorSet(
120
9926
          d_partialModel, TableauSizes(&d_tableau), BoundCountingLookup(*this)),
121
      d_tableau(),
122
      d_linEq(d_partialModel,
123
              d_tableau,
124
              d_rowTracking,
125
19852
              BasicVarModelUpdateCallBack(*this)),
126
      d_diosolver(context()),
127
      d_restartsCounter(0),
128
      d_tableauSizeHasBeenModified(false),
129
      d_tableauResetDensity(1.6),
130
      d_tableauResetPeriod(10),
131
      d_conflicts(context()),
132
19852
      d_blackBoxConflict(context(), Node::null()),
133
19852
      d_blackBoxConflictPf(context(), std::shared_ptr<ProofNode>(nullptr)),
134
      d_congruenceManager(context(),
135
                          userContext(),
136
                          d_constraintDatabase,
137
19852
                          SetupLiteralCallBack(*this),
138
                          d_partialModel,
139
                          RaiseEqualityEngineConflict(*this),
140
                          d_pnm),
141
9926
      d_cmEnabled(context(), options().arith.arithCongMan),
142
143
      d_dualSimplex(
144
19852
          d_linEq, d_errorSet, RaiseConflict(*this), TempVarMalloc(*this)),
145
      d_fcSimplex(
146
19852
          d_linEq, d_errorSet, RaiseConflict(*this), TempVarMalloc(*this)),
147
      d_soiSimplex(
148
19852
          d_linEq, d_errorSet, RaiseConflict(*this), TempVarMalloc(*this)),
149
      d_attemptSolSimplex(
150
19852
          d_linEq, d_errorSet, RaiseConflict(*this), TempVarMalloc(*this)),
151
      d_pass1SDP(NULL),
152
      d_otherSDP(NULL),
153
      d_lastContextIntegerAttempted(context(), -1),
154
155
      d_DELTA_ZERO(0),
156
      d_approxCuts(context()),
157
      d_fullCheckCounter(0),
158
      d_cutCount(context(), 0),
159
      d_cutInContext(context()),
160
      d_likelyIntegerInfeasible(context(), false),
161
      d_guessedCoeffSet(context(), false),
162
      d_guessedCoeffs(),
163
      d_treeLog(NULL),
164
      d_replayVariables(),
165
      d_replayConstraints(),
166
      d_lhsTmp(),
167
      d_approxStats(NULL),
168
9926
      d_attemptSolveIntTurnedOff(userContext(), 0),
169
      d_dioSolveResources(0),
170
      d_solveIntMaybeHelp(0u),
171
      d_solveIntAttempts(0u),
172
      d_newFacts(false),
173
      d_previousStatus(Result::SAT_UNKNOWN),
174
268002
      d_statistics("theory::arith::")
175
{
176
9926
}
177
178
29769
TheoryArithPrivate::~TheoryArithPrivate(){
179
9923
  if(d_treeLog != NULL){ delete d_treeLog; }
180
9923
  if(d_approxStats != NULL) { delete d_approxStats; }
181
19846
}
182
183
9887
bool TheoryArithPrivate::needsEqualityEngine(EeSetupInfo& esi)
184
{
185
9887
  if (!d_cmEnabled)
186
  {
187
    return false;
188
  }
189
9887
  return d_congruenceManager.needsEqualityEngine(esi);
190
}
191
9926
void TheoryArithPrivate::finishInit()
192
{
193
9926
  if (d_cmEnabled)
194
  {
195
9887
    eq::EqualityEngine* ee = d_containing.getEqualityEngine();
196
9887
    Assert(ee != nullptr);
197
9887
    d_congruenceManager.finishInit(ee);
198
  }
199
9926
}
200
201
static bool contains(const ConstraintCPVec& v, ConstraintP con){
202
  for(unsigned i = 0, N = v.size(); i < N; ++i){
203
    if(v[i] == con){
204
      return true;
205
    }
206
  }
207
  return false;
208
}
209
static void drop( ConstraintCPVec& v, ConstraintP con){
210
  size_t readPos, writePos, N;
211
  for(readPos = 0, writePos = 0, N = v.size(); readPos < N; ++readPos){
212
    ConstraintCP curr = v[readPos];
213
    if(curr != con){
214
      v[writePos] = curr;
215
      writePos++;
216
    }
217
  }
218
  v.resize(writePos);
219
}
220
221
222
static void resolve(ConstraintCPVec& buf, ConstraintP c, const ConstraintCPVec& pos, const ConstraintCPVec& neg){
223
  unsigned posPos CVC5_UNUSED = pos.size();
224
  for(unsigned i = 0, N = pos.size(); i < N; ++i){
225
    if(pos[i] == c){
226
      posPos = i;
227
    }else{
228
      buf.push_back(pos[i]);
229
    }
230
  }
231
  Assert(posPos < pos.size());
232
  ConstraintP negc = c->getNegation();
233
  unsigned negPos CVC5_UNUSED = neg.size();
234
  for(unsigned i = 0, N = neg.size(); i < N; ++i){
235
    if(neg[i] == negc){
236
      negPos = i;
237
    }else{
238
      buf.push_back(neg[i]);
239
    }
240
  }
241
  Assert(negPos < neg.size());
242
243
  // Assert(dnconf.getKind() == kind::AND);
244
  // Assert(upconf.getKind() == kind::AND);
245
  // Assert(dnpos < dnconf.getNumChildren());
246
  // Assert(uppos < upconf.getNumChildren());
247
  // Assert(equalUpToNegation(dnconf[dnpos], upconf[uppos]));
248
249
  // NodeBuilder nb(kind::AND);
250
  // dropPosition(nb, dnconf, dnpos);
251
  // dropPosition(nb, upconf, uppos);
252
  // return safeConstructNary(nb);
253
}
254
255
TheoryArithPrivate::ModelException::ModelException(TNode n, const char* msg)
256
{
257
  stringstream ss;
258
  ss << "Cannot construct a model for " << n << " as " << endl << msg;
259
  setMessage(ss.str());
260
}
261
TheoryArithPrivate::ModelException::~ModelException() {}
262
263
9926
TheoryArithPrivate::Statistics::Statistics(const std::string& name)
264
    : d_statAssertUpperConflicts(
265
19852
        smtStatisticsRegistry().registerInt(name + "AssertUpperConflicts")),
266
      d_statAssertLowerConflicts(
267
19852
          smtStatisticsRegistry().registerInt(name + "AssertLowerConflicts")),
268
      d_statUserVariables(
269
19852
          smtStatisticsRegistry().registerInt(name + "UserVariables")),
270
      d_statAuxiliaryVariables(
271
19852
          smtStatisticsRegistry().registerInt(name + "AuxiliaryVariables")),
272
      d_statDisequalitySplits(
273
19852
          smtStatisticsRegistry().registerInt(name + "DisequalitySplits")),
274
      d_statDisequalityConflicts(
275
19852
          smtStatisticsRegistry().registerInt(name + "DisequalityConflicts")),
276
      d_simplifyTimer(
277
19852
          smtStatisticsRegistry().registerTimer(name + "simplifyTimer")),
278
      d_staticLearningTimer(
279
19852
          smtStatisticsRegistry().registerTimer(name + "staticLearningTimer")),
280
      d_presolveTime(
281
19852
          smtStatisticsRegistry().registerTimer(name + "presolveTime")),
282
      d_newPropTime(
283
19852
          smtStatisticsRegistry().registerTimer(name + "newPropTimer")),
284
9926
      d_externalBranchAndBounds(smtStatisticsRegistry().registerInt(
285
19852
          name + "externalBranchAndBounds")),
286
      d_initialTableauSize(
287
19852
          smtStatisticsRegistry().registerInt(name + "initialTableauSize")),
288
      d_currSetToSmaller(
289
19852
          smtStatisticsRegistry().registerInt(name + "currSetToSmaller")),
290
      d_smallerSetToCurr(
291
19852
          smtStatisticsRegistry().registerInt(name + "smallerSetToCurr")),
292
      d_restartTimer(
293
19852
          smtStatisticsRegistry().registerTimer(name + "restartTimer")),
294
      d_boundComputationTime(
295
19852
          smtStatisticsRegistry().registerTimer(name + "bound::time")),
296
9926
      d_boundComputations(smtStatisticsRegistry().registerInt(
297
19852
          name + "bound::boundComputations")),
298
9926
      d_boundPropagations(smtStatisticsRegistry().registerInt(
299
19852
          name + "bound::boundPropagations")),
300
      d_unknownChecks(
301
19852
          smtStatisticsRegistry().registerInt(name + "status::unknowns")),
302
9926
      d_maxUnknownsInARow(smtStatisticsRegistry().registerInt(
303
19852
          name + "status::maxUnknownsInARow")),
304
9926
      d_avgUnknownsInARow(smtStatisticsRegistry().registerAverage(
305
19852
          name + "status::avgUnknownsInARow")),
306
9926
      d_revertsOnConflicts(smtStatisticsRegistry().registerInt(
307
19852
          name + "status::revertsOnConflicts")),
308
9926
      d_commitsOnConflicts(smtStatisticsRegistry().registerInt(
309
19852
          name + "status::commitsOnConflicts")),
310
9926
      d_nontrivialSatChecks(smtStatisticsRegistry().registerInt(
311
19852
          name + "status::nontrivialSatChecks")),
312
      d_replayLogRecCount(
313
19852
          smtStatisticsRegistry().registerInt(name + "z::approx::replay::rec")),
314
9926
      d_replayLogRecConflictEscalation(smtStatisticsRegistry().registerInt(
315
19852
          name + "z::approx::replay::rec::escalation")),
316
9926
      d_replayLogRecEarlyExit(smtStatisticsRegistry().registerInt(
317
19852
          name + "z::approx::replay::rec::earlyexit")),
318
9926
      d_replayBranchCloseFailures(smtStatisticsRegistry().registerInt(
319
19852
          name + "z::approx::replay::rec::branch::closefailures")),
320
9926
      d_replayLeafCloseFailures(smtStatisticsRegistry().registerInt(
321
19852
          name + "z::approx::replay::rec::leaf::closefailures")),
322
9926
      d_replayBranchSkips(smtStatisticsRegistry().registerInt(
323
19852
          name + "z::approx::replay::rec::branch::skips")),
324
9926
      d_mirCutsAttempted(smtStatisticsRegistry().registerInt(
325
19852
          name + "z::approx::cuts::mir::attempted")),
326
9926
      d_gmiCutsAttempted(smtStatisticsRegistry().registerInt(
327
19852
          name + "z::approx::cuts::gmi::attempted")),
328
9926
      d_branchCutsAttempted(smtStatisticsRegistry().registerInt(
329
19852
          name + "z::approx::cuts::branch::attempted")),
330
9926
      d_cutsReconstructed(smtStatisticsRegistry().registerInt(
331
19852
          name + "z::approx::cuts::reconstructed")),
332
9926
      d_cutsReconstructionFailed(smtStatisticsRegistry().registerInt(
333
19852
          name + "z::approx::cuts::reconstructed::failed")),
334
9926
      d_cutsProven(smtStatisticsRegistry().registerInt(
335
19852
          name + "z::approx::cuts::proofs")),
336
9926
      d_cutsProofFailed(smtStatisticsRegistry().registerInt(
337
19852
          name + "z::approx::cuts::proofs::failed")),
338
9926
      d_mipReplayLemmaCalls(smtStatisticsRegistry().registerInt(
339
19852
          name + "z::approx::external::calls")),
340
9926
      d_mipExternalCuts(smtStatisticsRegistry().registerInt(
341
19852
          name + "z::approx::external::cuts")),
342
9926
      d_mipExternalBranch(smtStatisticsRegistry().registerInt(
343
19852
          name + "z::approx::external::branches")),
344
9926
      d_inSolveInteger(smtStatisticsRegistry().registerInt(
345
19852
          name + "z::approx::inSolverInteger")),
346
9926
      d_branchesExhausted(smtStatisticsRegistry().registerInt(
347
19852
          name + "z::approx::exhausted::branches")),
348
9926
      d_execExhausted(smtStatisticsRegistry().registerInt(
349
19852
          name + "z::approx::exhausted::exec")),
350
9926
      d_pivotsExhausted(smtStatisticsRegistry().registerInt(
351
19852
          name + "z::approx::exhausted::pivots")),
352
      d_panicBranches(
353
19852
          smtStatisticsRegistry().registerInt(name + "z::arith::paniclemmas")),
354
      d_relaxCalls(
355
19852
          smtStatisticsRegistry().registerInt(name + "z::arith::relax::calls")),
356
9926
      d_relaxLinFeas(smtStatisticsRegistry().registerInt(
357
19852
          name + "z::arith::relax::feasible::res")),
358
9926
      d_relaxLinFeasFailures(smtStatisticsRegistry().registerInt(
359
19852
          name + "z::arith::relax::feasible::failures")),
360
9926
      d_relaxLinInfeas(smtStatisticsRegistry().registerInt(
361
19852
          name + "z::arith::relax::infeasible")),
362
9926
      d_relaxLinInfeasFailures(smtStatisticsRegistry().registerInt(
363
19852
          name + "z::arith::relax::infeasible::failures")),
364
9926
      d_relaxLinExhausted(smtStatisticsRegistry().registerInt(
365
19852
          name + "z::arith::relax::exhausted")),
366
      d_relaxOthers(
367
19852
          smtStatisticsRegistry().registerInt(name + "z::arith::relax::other")),
368
9926
      d_applyRowsDeleted(smtStatisticsRegistry().registerInt(
369
19852
          name + "z::arith::cuts::applyRowsDeleted")),
370
9926
      d_replaySimplexTimer(smtStatisticsRegistry().registerTimer(
371
19852
          name + "z::approx::replay::simplex::timer")),
372
9926
      d_replayLogTimer(smtStatisticsRegistry().registerTimer(
373
19852
          name + "z::approx::replay::log::timer")),
374
      d_solveIntTimer(
375
19852
          smtStatisticsRegistry().registerTimer(name + "z::solveInt::timer")),
376
9926
      d_solveRealRelaxTimer(smtStatisticsRegistry().registerTimer(
377
19852
          name + "z::solveRealRelax::timer")),
378
      d_solveIntCalls(
379
19852
          smtStatisticsRegistry().registerInt(name + "z::solveInt::calls")),
380
9926
      d_solveStandardEffort(smtStatisticsRegistry().registerInt(
381
19852
          name + "z::solveInt::calls::standardEffort")),
382
      d_approxDisabled(
383
19852
          smtStatisticsRegistry().registerInt(name + "z::approxDisabled")),
384
      d_replayAttemptFailed(
385
19852
          smtStatisticsRegistry().registerInt(name + "z::replayAttemptFailed")),
386
9926
      d_cutsRejectedDuringReplay(smtStatisticsRegistry().registerInt(
387
19852
          name + "z::approx::replay::cuts::rejected")),
388
9926
      d_cutsRejectedDuringLemmas(smtStatisticsRegistry().registerInt(
389
19852
          name + "z::approx::external::cuts::rejected")),
390
9926
      d_satPivots(smtStatisticsRegistry().registerHistogram<uint32_t>(
391
19852
          name + "pivots::sat")),
392
9926
      d_unsatPivots(smtStatisticsRegistry().registerHistogram<uint32_t>(
393
19852
          name + "pivots::unsat")),
394
9926
      d_unknownPivots(smtStatisticsRegistry().registerHistogram<uint32_t>(
395
19852
          name + "pivots::unknown")),
396
9926
      d_solveIntModelsAttempts(smtStatisticsRegistry().registerInt(
397
19852
          name + "z::solveInt::models::attempts")),
398
9926
      d_solveIntModelsSuccessful(smtStatisticsRegistry().registerInt(
399
19852
          name + "zzz::solveInt::models::successful")),
400
9926
      d_mipTimer(smtStatisticsRegistry().registerTimer(
401
19852
          name + "z::approx::mip::timer")),
402
      d_lpTimer(
403
19852
          smtStatisticsRegistry().registerTimer(name + "z::approx::lp::timer")),
404
9926
      d_mipProofsAttempted(smtStatisticsRegistry().registerInt(
405
19852
          name + "z::mip::proofs::attempted")),
406
9926
      d_mipProofsSuccessful(smtStatisticsRegistry().registerInt(
407
19852
          name + "z::mip::proofs::successful")),
408
9926
      d_numBranchesFailed(smtStatisticsRegistry().registerInt(
409
724598
          name + "z::mip::branch::proof::failed"))
410
{
411
9926
}
412
413
bool complexityBelow(const DenseMap<Rational>& row, uint32_t cap){
414
  DenseMap<Rational>::const_iterator riter, rend;
415
  for(riter=row.begin(), rend=row.end(); riter != rend; ++riter){
416
    ArithVar v = *riter;
417
    const Rational& q = row[v];
418
    if(q.complexity() > cap){
419
      return false;
420
    }
421
  }
422
  return true;
423
}
424
425
186039
bool TheoryArithPrivate::isProofEnabled() const
426
{
427
186039
  return d_pnm != nullptr;
428
}
429
430
80562
void TheoryArithPrivate::raiseConflict(ConstraintCP a, InferenceId id){
431
80562
  Assert(a->inConflict());
432
161124
  d_conflicts.push_back(std::make_pair(a, id));
433
80562
}
434
435
2391
void TheoryArithPrivate::raiseBlackBoxConflict(Node bb,
436
                                               std::shared_ptr<ProofNode> pf)
437
{
438
2391
  Debug("arith::bb") << "raiseBlackBoxConflict: " << bb << std::endl;
439
2391
  if (d_blackBoxConflict.get().isNull())
440
  {
441
2391
    if (isProofEnabled())
442
    {
443
413
      Debug("arith::bb") << "  with proof " << pf << std::endl;
444
413
      d_blackBoxConflictPf.set(pf);
445
    }
446
2391
    d_blackBoxConflict = bb;
447
  }
448
2391
}
449
450
17585692
bool TheoryArithPrivate::anyConflict() const
451
{
452
17585692
  return !conflictQueueEmpty() || !d_blackBoxConflict.get().isNull();
453
}
454
455
57086
void TheoryArithPrivate::revertOutOfConflict(){
456
57086
  d_partialModel.revertAssignmentChanges();
457
57086
  clearUpdates();
458
57086
  d_currentPropagationList.clear();
459
57086
}
460
461
1743056
void TheoryArithPrivate::clearUpdates(){
462
1743056
  d_updatedBounds.purge();
463
1743056
}
464
465
// void TheoryArithPrivate::raiseConflict(ConstraintCP a, ConstraintCP b){
466
//   ConstraintCPVec v;
467
//   v.push_back(a);
468
//   v.push_back(b);
469
//   d_conflicts.push_back(v);
470
// }
471
472
// void TheoryArithPrivate::raiseConflict(ConstraintCP a, ConstraintCP b, ConstraintCP c){
473
//   ConstraintCPVec v;
474
//   v.push_back(a);
475
//   v.push_back(b);
476
//   v.push_back(c);
477
//   d_conflicts.push_back(v);
478
// }
479
480
491314
void TheoryArithPrivate::zeroDifferenceDetected(ArithVar x){
481
491314
  if(d_cmEnabled){
482
491314
    Assert(d_congruenceManager.isWatchedVariable(x));
483
491314
    Assert(d_partialModel.upperBoundIsZero(x));
484
491314
    Assert(d_partialModel.lowerBoundIsZero(x));
485
486
491314
    ConstraintP lb = d_partialModel.getLowerBoundConstraint(x);
487
491314
    ConstraintP ub = d_partialModel.getUpperBoundConstraint(x);
488
489
491314
    if(lb->isEquality()){
490
239866
      d_congruenceManager.watchedVariableIsZero(lb);
491
251448
    }else if(ub->isEquality()){
492
      d_congruenceManager.watchedVariableIsZero(ub);
493
    }else{
494
251448
      d_congruenceManager.watchedVariableIsZero(lb, ub);
495
    }
496
  }
497
491314
}
498
499
bool TheoryArithPrivate::getSolveIntegerResource(){
500
  if(d_attemptSolveIntTurnedOff > 0){
501
    d_attemptSolveIntTurnedOff = d_attemptSolveIntTurnedOff - 1;
502
    return false;
503
  }else{
504
    return true;
505
  }
506
}
507
508
2592
bool TheoryArithPrivate::getDioCuttingResource(){
509
2592
  if(d_dioSolveResources > 0){
510
1919
    d_dioSolveResources--;
511
1919
    if(d_dioSolveResources == 0){
512
135
      d_dioSolveResources = -options().arith.rrTurns;
513
    }
514
1919
    return true;
515
  }else{
516
673
    d_dioSolveResources++;
517
673
    if(d_dioSolveResources >= 0){
518
409
      d_dioSolveResources = options().arith.dioSolverTurns;
519
    }
520
673
    return false;
521
  }
522
}
523
524
/* procedure AssertLower( x_i >= c_i ) */
525
1913532
bool TheoryArithPrivate::AssertLower(ConstraintP constraint){
526
1913532
  Assert(constraint != NullConstraint);
527
1913532
  Assert(constraint->isLowerBound());
528
1913532
  Assert(constraint->isTrue());
529
1913532
  Assert(!constraint->negationHasProof());
530
531
1913532
  ArithVar x_i = constraint->getVariable();
532
1913532
  const DeltaRational& c_i = constraint->getValue();
533
534
1913532
  Debug("arith") << "AssertLower(" << x_i << " " << c_i << ")"<< std::endl;
535
536
1913532
  Assert(!isInteger(x_i) || c_i.isIntegral());
537
538
  //TODO Relax to less than?
539
1913532
  if(d_partialModel.lessThanLowerBound(x_i, c_i)){
540
798088
    return false; //sat
541
  }
542
543
1115444
  int cmpToUB = d_partialModel.cmpToUpperBound(x_i, c_i);
544
1115444
  if(cmpToUB > 0){ //  c_i < \lowerbound(x_i)
545
775
    ConstraintP ubc = d_partialModel.getUpperBoundConstraint(x_i);
546
775
    ConstraintP negation = constraint->getNegation();
547
775
    negation->impliedByUnate(ubc, true);
548
549
775
    raiseConflict(constraint, InferenceId::ARITH_CONF_LOWER);
550
551
775
    ++(d_statistics.d_statAssertLowerConflicts);
552
775
    return true;
553
1114669
  }else if(cmpToUB == 0){
554
274519
    if(isInteger(x_i)){
555
76565
      d_constantIntegerVariables.push_back(x_i);
556
76565
      Debug("dio::push") << "dio::push " << x_i << endl;
557
    }
558
274519
    ConstraintP ub = d_partialModel.getUpperBoundConstraint(x_i);
559
560
274519
    if(d_cmEnabled){
561
274519
      if(!d_congruenceManager.isWatchedVariable(x_i) || c_i.sgn() != 0){
562
        // if it is not a watched variable report it
563
        // if it is is a watched variable and c_i == 0,
564
        // let zeroDifferenceDetected(x_i) catch this
565
92589
        d_congruenceManager.equalsConstant(constraint, ub);
566
      }
567
    }
568
569
274519
    const ValueCollection& vc = constraint->getValueCollection();
570
274519
    if(vc.hasEquality()){
571
194113
      Assert(vc.hasDisequality());
572
194113
      ConstraintP eq = vc.getEquality();
573
194113
      ConstraintP diseq = vc.getDisequality();
574
      // x <= b, x >= b |= x = b
575
      // (x > b or x < b or x = b)
576
194113
      Debug("arith::eq") << "lb == ub, propagate eq" << eq << endl;
577
194113
      bool triConflict = diseq->isTrue();
578
579
194113
      if(!eq->isTrue()){
580
189112
        eq->impliedByTrichotomy(constraint, ub, triConflict);
581
189112
        eq->tryToPropagate();
582
      }
583
194113
      if(triConflict){
584
        ++(d_statistics.d_statDisequalityConflicts);
585
        raiseConflict(eq, InferenceId::ARITH_CONF_TRICHOTOMY);
586
        return true;
587
      }
588
    }
589
  }else{
590
    // l <= x <= u and l < u
591
840150
    Assert(cmpToUB < 0);
592
840150
    const ValueCollection& vc = constraint->getValueCollection();
593
594
840150
    if(vc.hasDisequality()){
595
236016
      const ConstraintP diseq = vc.getDisequality();
596
236016
      if(diseq->isTrue()){
597
12888
        const ConstraintP ub = d_constraintDatabase.ensureConstraint(const_cast<ValueCollection&>(vc), UpperBound);
598
12888
        ConstraintP negUb = ub->getNegation();
599
600
        // l <= x, l != x |= l < x
601
        // |= not (l >= x)
602
12888
        bool ubInConflict = ub->hasProof();
603
12888
        bool learnNegUb = !(negUb->hasProof());
604
12888
        if(learnNegUb){
605
12888
          negUb->impliedByTrichotomy(constraint, diseq, ubInConflict);
606
12888
          negUb->tryToPropagate();
607
        }
608
12888
        if(ubInConflict){
609
          raiseConflict(ub, InferenceId::ARITH_CONF_TRICHOTOMY);
610
          return true;
611
12888
        }else if(learnNegUb){
612
12888
          d_learnedBounds.push_back(negUb);
613
        }
614
      }
615
    }
616
  }
617
618
1114669
  d_currentPropagationList.push_back(constraint);
619
1114669
  d_currentPropagationList.push_back(d_partialModel.getLowerBoundConstraint(x_i));
620
621
1114669
  d_partialModel.setLowerBoundConstraint(constraint);
622
623
1114669
  if(d_cmEnabled){
624
1114370
    if(d_congruenceManager.isWatchedVariable(x_i)){
625
665404
      int sgn = c_i.sgn();
626
665404
      if(sgn > 0){
627
180470
        d_congruenceManager.watchedVariableCannotBeZero(constraint);
628
484934
      }else if(sgn == 0 && d_partialModel.upperBoundIsZero(x_i)){
629
181930
        zeroDifferenceDetected(x_i);
630
      }
631
    }
632
  }
633
634
1114669
  d_updatedBounds.softAdd(x_i);
635
636
1114669
  if(Debug.isOn("model")) {
637
    Debug("model") << "before" << endl;
638
    d_partialModel.printModel(x_i);
639
    d_tableau.debugPrintIsBasic(x_i);
640
  }
641
642
1114669
  if(!d_tableau.isBasic(x_i)){
643
379192
    if(d_partialModel.getAssignment(x_i) < c_i){
644
59446
      d_linEq.update(x_i, c_i);
645
    }
646
  }else{
647
735477
    d_errorSet.signalVariable(x_i);
648
  }
649
650
1114669
  if(Debug.isOn("model")) {
651
    Debug("model") << "after" << endl;
652
    d_partialModel.printModel(x_i);
653
    d_tableau.debugPrintIsBasic(x_i);
654
 }
655
656
1114669
  return false; //sat
657
}
658
659
/* procedure AssertUpper( x_i <= c_i) */
660
1921592
bool TheoryArithPrivate::AssertUpper(ConstraintP constraint){
661
1921592
  Assert(constraint != NullConstraint);
662
1921592
  Assert(constraint->isUpperBound());
663
1921592
  Assert(constraint->isTrue());
664
1921592
  Assert(!constraint->negationHasProof());
665
666
1921592
  ArithVar x_i = constraint->getVariable();
667
1921592
  const DeltaRational& c_i = constraint->getValue();
668
669
1921592
  Debug("arith") << "AssertUpper(" << x_i << " " << c_i << ")"<< std::endl;
670
671
672
  //Too strong because of rounding with integers
673
  //Assert(!constraint->hasLiteral() || original == constraint->getLiteral());
674
1921592
  Assert(!isInteger(x_i) || c_i.isIntegral());
675
676
1921592
  Debug("arith") << "AssertUpper(" << x_i << " " << c_i << ")"<< std::endl;
677
678
1921592
  if(d_partialModel.greaterThanUpperBound(x_i, c_i) ){ // \upperbound(x_i) <= c_i
679
931803
    return false; //sat
680
  }
681
682
  // cmpToLb =  \lowerbound(x_i).cmp(c_i)
683
989789
  int cmpToLB = d_partialModel.cmpToLowerBound(x_i, c_i);
684
989789
  if( cmpToLB < 0 ){ //  \upperbound(x_i) < \lowerbound(x_i)
685
    // l_i <= x_i and c_i < l_i |= c_i < x_i
686
    // or ... |= not (x_i <= c_i)
687
2195
    ConstraintP lbc = d_partialModel.getLowerBoundConstraint(x_i);
688
2195
    ConstraintP negConstraint = constraint->getNegation();
689
2195
    negConstraint->impliedByUnate(lbc, true);
690
2195
    raiseConflict(constraint, InferenceId::ARITH_CONF_UPPER);
691
2195
    ++(d_statistics.d_statAssertUpperConflicts);
692
2195
    return true;
693
987594
  }else if(cmpToLB == 0){ // \lowerBound(x_i) == \upperbound(x_i)
694
145738
    if(isInteger(x_i)){
695
95635
      d_constantIntegerVariables.push_back(x_i);
696
95635
      Debug("dio::push") << "dio::push " << x_i << endl;
697
    }
698
699
145738
    const ValueCollection& vc = constraint->getValueCollection();
700
145738
    ConstraintP lb = d_partialModel.getLowerBoundConstraint(x_i);
701
145738
    if(d_cmEnabled){
702
145738
      if(!d_congruenceManager.isWatchedVariable(x_i) || c_i.sgn() != 0){
703
        // if it is not a watched variable report it
704
        // if it is is a watched variable and c_i == 0,
705
        // let zeroDifferenceDetected(x_i) catch this
706
76220
        d_congruenceManager.equalsConstant(lb, constraint);
707
      }
708
    }
709
710
145738
    if(vc.hasDisequality()){
711
115804
      Assert(vc.hasDisequality());
712
115804
      ConstraintP eq = vc.getEquality();
713
115804
      ConstraintP diseq = vc.getDisequality();
714
      // x <= b, x >= b |= x = b
715
      // (x > b or x < b or x = b)
716
115804
      Debug("arith::eq") << "lb == ub, propagate eq" << eq << endl;
717
115804
      bool triConflict = diseq->isTrue();
718
115804
      if(!eq->isTrue()){
719
84929
        eq->impliedByTrichotomy(constraint, lb, triConflict);
720
84929
        eq->tryToPropagate();
721
      }
722
115804
      if(triConflict){
723
4
        ++(d_statistics.d_statDisequalityConflicts);
724
4
        raiseConflict(eq, InferenceId::ARITH_CONF_TRICHOTOMY);
725
4
        return true;
726
      }
727
    }
728
841856
  }else if(cmpToLB > 0){
729
    // l <= x <= u and l < u
730
841856
    Assert(cmpToLB > 0);
731
841856
    const ValueCollection& vc = constraint->getValueCollection();
732
733
841856
    if(vc.hasDisequality()){
734
313412
      const ConstraintP diseq = vc.getDisequality();
735
313412
      if(diseq->isTrue()){
736
38809
        const ConstraintP lb = d_constraintDatabase.ensureConstraint(const_cast<ValueCollection&>(vc), LowerBound);
737
38809
        ConstraintP negLb = lb->getNegation();
738
739
        // x <= u, u != x |= u < x
740
        // |= not (u >= x)
741
38809
        bool lbInConflict = lb->hasProof();
742
38809
        bool learnNegLb = !(negLb->hasProof());
743
38809
        if(learnNegLb){
744
38808
          negLb->impliedByTrichotomy(constraint, diseq, lbInConflict);
745
38808
          negLb->tryToPropagate();
746
        }
747
38809
        if(lbInConflict){
748
          raiseConflict(lb, InferenceId::ARITH_CONF_TRICHOTOMY);
749
          return true;
750
38809
        }else if(learnNegLb){
751
38808
          d_learnedBounds.push_back(negLb);
752
        }
753
      }
754
    }
755
  }
756
757
987590
  d_currentPropagationList.push_back(constraint);
758
987590
  d_currentPropagationList.push_back(d_partialModel.getUpperBoundConstraint(x_i));
759
  //It is fine if this is NullConstraint
760
761
987590
  d_partialModel.setUpperBoundConstraint(constraint);
762
763
987590
  if(d_cmEnabled){
764
987269
    if(d_congruenceManager.isWatchedVariable(x_i)){
765
638988
      int sgn = c_i.sgn();
766
638988
      if(sgn < 0){
767
294983
        d_congruenceManager.watchedVariableCannotBeZero(constraint);
768
344005
      }else if(sgn == 0 && d_partialModel.lowerBoundIsZero(x_i)){
769
69518
        zeroDifferenceDetected(x_i);
770
      }
771
    }
772
  }
773
774
987590
  d_updatedBounds.softAdd(x_i);
775
776
987590
  if(Debug.isOn("model")) {
777
    Debug("model") << "before" << endl;
778
    d_partialModel.printModel(x_i);
779
    d_tableau.debugPrintIsBasic(x_i);
780
  }
781
782
987590
  if(!d_tableau.isBasic(x_i)){
783
379126
    if(d_partialModel.getAssignment(x_i) > c_i){
784
45747
      d_linEq.update(x_i, c_i);
785
    }
786
  }else{
787
608464
    d_errorSet.signalVariable(x_i);
788
  }
789
790
987590
  if(Debug.isOn("model")) {
791
    Debug("model") << "after" << endl;
792
    d_partialModel.printModel(x_i);
793
    d_tableau.debugPrintIsBasic(x_i);
794
  }
795
796
987590
  return false; //sat
797
}
798
799
800
/* procedure AssertEquality( x_i == c_i ) */
801
1080291
bool TheoryArithPrivate::AssertEquality(ConstraintP constraint){
802
1080291
  Assert(constraint != NullConstraint);
803
1080291
  Assert(constraint->isEquality());
804
1080291
  Assert(constraint->isTrue());
805
1080291
  Assert(!constraint->negationHasProof());
806
807
1080291
  ArithVar x_i = constraint->getVariable();
808
1080291
  const DeltaRational& c_i = constraint->getValue();
809
810
1080291
  Debug("arith") << "AssertEquality(" << x_i << " " << c_i << ")"<< std::endl;
811
812
  //Should be fine in integers
813
1080291
  Assert(!isInteger(x_i) || c_i.isIntegral());
814
815
1080291
  int cmpToLB = d_partialModel.cmpToLowerBound(x_i, c_i);
816
1080291
  int cmpToUB = d_partialModel.cmpToUpperBound(x_i, c_i);
817
818
  // u_i <= c_i <= l_i
819
  // This can happen if both c_i <= x_i and x_i <= c_i are in the system.
820
1080291
  if(cmpToUB >= 0 && cmpToLB <= 0){
821
45988
    return false; //sat
822
  }
823
824
1034303
  if(cmpToUB > 0 || cmpToLB < 0){
825
3372
    ConstraintP cb = (cmpToUB > 0) ?  d_partialModel.getUpperBoundConstraint(x_i) :
826
3372
      d_partialModel.getLowerBoundConstraint(x_i);
827
2188
    ConstraintP diseq = constraint->getNegation();
828
2188
    Assert(!diseq->isTrue());
829
2188
    diseq->impliedByUnate(cb, true);
830
2188
    raiseConflict(constraint, InferenceId::ARITH_CONF_EQ);
831
2188
    return true;
832
  }
833
834
1032115
  Assert(cmpToUB <= 0);
835
1032115
  Assert(cmpToLB >= 0);
836
1032115
  Assert(cmpToUB < 0 || cmpToLB > 0);
837
838
1032115
  if(isInteger(x_i)){
839
986625
    d_constantIntegerVariables.push_back(x_i);
840
986625
    Debug("dio::push") << "dio::push " << x_i << endl;
841
  }
842
843
  // Don't bother to check whether x_i != c_i is in d_diseq
844
  // The a and (not a) should never be on the fact queue
845
1032115
  d_currentPropagationList.push_back(constraint);
846
1032115
  d_currentPropagationList.push_back(d_partialModel.getLowerBoundConstraint(x_i));
847
1032115
  d_currentPropagationList.push_back(d_partialModel.getUpperBoundConstraint(x_i));
848
849
1032115
  d_partialModel.setUpperBoundConstraint(constraint);
850
1032115
  d_partialModel.setLowerBoundConstraint(constraint);
851
852
1032115
  if(d_cmEnabled){
853
1031324
    if(d_congruenceManager.isWatchedVariable(x_i)){
854
276899
      int sgn = c_i.sgn();
855
276899
      if(sgn == 0){
856
239866
        zeroDifferenceDetected(x_i);
857
      }else{
858
37033
        d_congruenceManager.watchedVariableCannotBeZero(constraint);
859
37033
        d_congruenceManager.equalsConstant(constraint);
860
      }
861
    }else{
862
754425
      d_congruenceManager.equalsConstant(constraint);
863
    }
864
  }
865
866
1032115
  d_updatedBounds.softAdd(x_i);
867
868
1032115
  if(Debug.isOn("model")) {
869
    Debug("model") << "before" << endl;
870
    d_partialModel.printModel(x_i);
871
    d_tableau.debugPrintIsBasic(x_i);
872
  }
873
874
1032115
  if(!d_tableau.isBasic(x_i)){
875
559226
    if(!(d_partialModel.getAssignment(x_i) == c_i)){
876
60398
      d_linEq.update(x_i, c_i);
877
    }
878
  }else{
879
472889
    d_errorSet.signalVariable(x_i);
880
  }
881
882
1032115
  if(Debug.isOn("model")) {
883
    Debug("model") << "after" << endl;
884
    d_partialModel.printModel(x_i);
885
    d_tableau.debugPrintIsBasic(x_i);
886
  }
887
888
1032115
  return false;
889
}
890
891
892
/* procedure AssertDisequality( x_i != c_i ) */
893
807972
bool TheoryArithPrivate::AssertDisequality(ConstraintP constraint){
894
807972
  Assert(constraint != NullConstraint);
895
807972
  Assert(constraint->isDisequality());
896
807972
  Assert(constraint->isTrue());
897
807972
  Assert(!constraint->negationHasProof());
898
899
807972
  ArithVar x_i = constraint->getVariable();
900
807972
  const DeltaRational& c_i = constraint->getValue();
901
807972
  Debug("arith") << "AssertDisequality(" << x_i << " " << c_i << ")"<< std::endl;
902
903
  //Should be fine in integers
904
807972
  Assert(!isInteger(x_i) || c_i.isIntegral());
905
906
807972
  if(d_cmEnabled){
907
807691
    if(d_congruenceManager.isWatchedVariable(x_i)){
908
180612
      int sgn = c_i.sgn();
909
180612
      if(sgn == 0){
910
156796
        d_congruenceManager.watchedVariableCannotBeZero(constraint);
911
      }
912
    }
913
  }
914
915
807972
  const ValueCollection& vc = constraint->getValueCollection();
916
807972
  if(vc.hasLowerBound() && vc.hasUpperBound()){
917
357987
    const ConstraintP lb = vc.getLowerBound();
918
357987
    const ConstraintP ub = vc.getUpperBound();
919
357987
    if(lb->isTrue() && ub->isTrue()){
920
87
      ConstraintP eq = constraint->getNegation();
921
87
      eq->impliedByTrichotomy(lb, ub, true);
922
87
      raiseConflict(constraint, InferenceId::ARITH_CONF_TRICHOTOMY);
923
      //in conflict
924
87
      ++(d_statistics.d_statDisequalityConflicts);
925
87
      return true;
926
    }
927
  }
928
807885
  if(vc.hasLowerBound() ){
929
409559
    const ConstraintP lb = vc.getLowerBound();
930
409559
    if(lb->isTrue()){
931
127391
      const ConstraintP ub = d_constraintDatabase.ensureConstraint(const_cast<ValueCollection&>(vc), UpperBound);
932
127391
      Assert(!ub->isTrue());
933
127391
      Debug("arith::eq") << "propagate UpperBound " << constraint << lb << ub << endl;
934
127391
      const ConstraintP negUb = ub->getNegation();
935
127391
      if(!negUb->isTrue()){
936
68651
        negUb->impliedByTrichotomy(constraint, lb, false);
937
68651
        negUb->tryToPropagate();
938
68651
        d_learnedBounds.push_back(negUb);
939
      }
940
    }
941
  }
942
807885
  if(vc.hasUpperBound()){
943
415727
    const ConstraintP ub = vc.getUpperBound();
944
415727
    if(ub->isTrue()){
945
88434
      const ConstraintP lb = d_constraintDatabase.ensureConstraint(const_cast<ValueCollection&>(vc), LowerBound);
946
88434
      Assert(!lb->isTrue());
947
948
88434
      Debug("arith::eq") << "propagate LowerBound " << constraint << lb << ub << endl;
949
88434
      const ConstraintP negLb = lb->getNegation();
950
88434
      if(!negLb->isTrue()){
951
15316
        negLb->impliedByTrichotomy(constraint, ub, false);
952
15316
        negLb->tryToPropagate();
953
15316
        d_learnedBounds.push_back(negLb);
954
      }
955
    }
956
  }
957
958
807885
  bool split = constraint->isSplit();
959
960
807885
  if(!split && c_i == d_partialModel.getAssignment(x_i)){
961
15514
    Debug("arith::eq") << "lemma now! " << constraint << endl;
962
15514
    outputTrustedLemma(constraint->split(), InferenceId::ARITH_SPLIT_DEQ);
963
15514
    return false;
964
792371
  }else if(d_partialModel.strictlyLessThanLowerBound(x_i, c_i)){
965
240990
    Debug("arith::eq") << "can drop as less than lb" << constraint << endl;
966
551381
  }else if(d_partialModel.strictlyGreaterThanUpperBound(x_i, c_i)){
967
212008
    Debug("arith::eq") << "can drop as less than ub" << constraint << endl;
968
339373
  }else if(!split){
969
198744
    Debug("arith::eq") << "push back" << constraint << endl;
970
198744
    d_diseqQueue.push(constraint);
971
198744
    d_partialModel.invalidateDelta();
972
  }else{
973
140629
    Debug("arith::eq") << "skipping already split " << constraint << endl;
974
  }
975
792371
  return false;
976
}
977
978
696570
void TheoryArithPrivate::notifySharedTerm(TNode n)
979
{
980
696570
  Debug("arith::notifySharedTerm") << "notifySharedTerm: " << n << endl;
981
696570
  if(n.isConst()){
982
83005
    d_partialModel.invalidateDelta();
983
  }
984
696570
  if(!n.isConst() && !isSetup(n)){
985
558652
    Polynomial poly = Polynomial::parsePolynomial(n);
986
558652
    Polynomial::iterator it = poly.begin();
987
558652
    Polynomial::iterator it_end = poly.end();
988
1505488
    for (; it != it_end; ++ it) {
989
1226162
      Monomial m = *it;
990
613081
      if (!m.isConstant() && !isSetup(m.getVarList().getNode())) {
991
5634
        setupVariableList(m.getVarList());
992
      }
993
    }
994
  }
995
696570
}
996
997
2981
Node TheoryArithPrivate::getModelValue(TNode term) {
998
  try{
999
5962
    const DeltaRational drv = getDeltaValue(term);
1000
2981
    const Rational& delta = d_partialModel.getDelta();
1001
5962
    const Rational qmodel = drv.substituteDelta( delta );
1002
2981
    return mkRationalNode( qmodel );
1003
  } catch (DeltaRationalException& dr) {
1004
    return Node::null();
1005
  } catch (ModelException& me) {
1006
    return Node::null();
1007
  }
1008
}
1009
1010
11654
Theory::PPAssertStatus TheoryArithPrivate::ppAssert(
1011
    TrustNode tin, TrustSubstitutionMap& outSubstitutions)
1012
{
1013
23308
  TimerStat::CodeTimer codeTimer(d_statistics.d_simplifyTimer);
1014
23308
  TNode in = tin.getNode();
1015
11654
  Debug("simplify") << "TheoryArithPrivate::solve(" << in << ")" << endl;
1016
1017
1018
  // Solve equalities
1019
23308
  Rational minConstant = 0;
1020
23308
  Node minMonomial;
1021
23308
  Node minVar;
1022
28686
  if (in.getKind() == kind::EQUAL &&
1023
17032
      Theory::theoryOf(in[0].getType()) == THEORY_ARITH) {
1024
4189
    Comparison cmp = Comparison::parseNormalForm(in);
1025
1026
4189
    Polynomial left = cmp.getLeft();
1027
1028
4189
    Monomial m = left.getHead();
1029
2689
    if (m.getVarList().singleton()){
1030
5266
      VarList vl = m.getVarList();
1031
5266
      Node var = vl.getNode();
1032
2633
      if (var.isVar())
1033
      {
1034
        // if vl.isIntegral then m.getConstant().isOne()
1035
1401
        if(!vl.isIntegral() || m.getConstant().isOne()){
1036
1389
          minVar = var;
1037
        }
1038
      }
1039
    }
1040
1041
    // Solve for variable
1042
2689
    if (!minVar.isNull()) {
1043
1589
      Polynomial right = cmp.getRight();
1044
1589
      Node elim = right.getNode();
1045
      // ax + p = c -> (ax + p) -ax - c = -ax
1046
      // x = (p - ax - c) * -1/a
1047
      // Add the substitution if not recursive
1048
1389
      Assert(elim == Rewriter::rewrite(elim));
1049
1050
1389
      if (right.size() > options().arith.ppAssertMaxSubSize)
1051
      {
1052
218
        Debug("simplify")
1053
            << "TheoryArithPrivate::solve(): did not substitute due to the "
1054
109
               "right hand side containing too many terms: "
1055
109
            << minVar << ":" << elim << endl;
1056
109
        Debug("simplify") << right.size() << endl;
1057
      }
1058
1280
      else if (d_containing.isLegalElimination(minVar, elim))
1059
      {
1060
        // cannot eliminate integers here unless we know the resulting
1061
        // substitution is integral
1062
2378
        Debug("simplify") << "TheoryArithPrivate::solve(): substitution "
1063
1189
                          << minVar << " |-> " << elim << endl;
1064
1065
1189
        outSubstitutions.addSubstitutionSolved(minVar, elim, tin);
1066
1189
        return Theory::PP_ASSERT_STATUS_SOLVED;
1067
      }
1068
      else
1069
      {
1070
182
        Debug("simplify") << "TheoryArithPrivate::solve(): can't substitute "
1071
182
                          << minVar << ":" << minVar.getType() << " |-> "
1072
91
                          << elim << ":" << elim.getType() << endl;
1073
      }
1074
    }
1075
  }
1076
1077
  // If a relation, remember the bound
1078
10465
  switch(in.getKind()) {
1079
5793
  case kind::LEQ:
1080
  case kind::LT:
1081
  case kind::GEQ:
1082
  case kind::GT:
1083
5793
    if (in[0].isVar()) {
1084
2475
      d_learner.addBound(in);
1085
    }
1086
5793
    break;
1087
4672
  default:
1088
    // Do nothing
1089
4672
    break;
1090
  }
1091
1092
10465
  return Theory::PP_ASSERT_STATUS_UNSOLVED;
1093
}
1094
1095
105454
void TheoryArithPrivate::ppStaticLearn(TNode n, NodeBuilder& learned)
1096
{
1097
210908
  TimerStat::CodeTimer codeTimer(d_statistics.d_staticLearningTimer);
1098
1099
105454
  d_learner.staticLearning(n, learned);
1100
105454
}
1101
1102
ArithVar TheoryArithPrivate::findShortestBasicRow(ArithVar variable){
1103
  ArithVar bestBasic = ARITHVAR_SENTINEL;
1104
  uint64_t bestRowLength = std::numeric_limits<uint64_t>::max();
1105
1106
  Tableau::ColIterator basicIter = d_tableau.colIterator(variable);
1107
  for(; !basicIter.atEnd(); ++basicIter){
1108
    const Tableau::Entry& entry = *basicIter;
1109
    Assert(entry.getColVar() == variable);
1110
    RowIndex ridx = entry.getRowIndex();
1111
    ArithVar basic = d_tableau.rowIndexToBasic(ridx);
1112
    uint32_t rowLength = d_tableau.getRowLength(ridx);
1113
    if((rowLength < bestRowLength) ||
1114
       (rowLength == bestRowLength && basic < bestBasic)){
1115
      bestBasic = basic;
1116
      bestRowLength = rowLength;
1117
    }
1118
  }
1119
  Assert(bestBasic == ARITHVAR_SENTINEL
1120
         || bestRowLength < std::numeric_limits<uint32_t>::max());
1121
  return bestBasic;
1122
}
1123
1124
67853
void TheoryArithPrivate::setupVariable(const Variable& x){
1125
135706
  Node n = x.getNode();
1126
1127
67853
  Assert(!isSetup(n));
1128
1129
67853
  ++(d_statistics.d_statUserVariables);
1130
67853
  requestArithVar(n, false,  false);
1131
  //ArithVar varN = requestArithVar(n,false);
1132
  //setupInitialValue(varN);
1133
1134
67853
  markSetup(n);
1135
67853
}
1136
1137
69369
void TheoryArithPrivate::setupVariableList(const VarList& vl){
1138
69369
  Assert(!vl.empty());
1139
1140
138738
  TNode vlNode = vl.getNode();
1141
69369
  Assert(!isSetup(vlNode));
1142
69369
  Assert(!d_partialModel.hasArithVar(vlNode));
1143
1144
145010
  for(VarList::iterator i = vl.begin(), end = vl.end(); i != end; ++i){
1145
151282
    Variable var = *i;
1146
1147
75641
    if(!isSetup(var.getNode())){
1148
67853
      setupVariable(var);
1149
    }
1150
  }
1151
1152
69369
  if(!vl.singleton()){
1153
    // vl is the product of at least 2 variables
1154
    // vl : (* v1 v2 ...)
1155
2514
    if (logicInfo().isLinear())
1156
    {
1157
1
      throw LogicException("A non-linear fact was asserted to arithmetic in a linear logic.");
1158
    }
1159
2513
    d_foundNl = true;
1160
1161
2513
    ++(d_statistics.d_statUserVariables);
1162
2513
    requestArithVar(vlNode, false, false);
1163
    //ArithVar av = requestArithVar(vlNode, false);
1164
    //setupInitialValue(av);
1165
1166
2513
    markSetup(vlNode);
1167
  }
1168
133710
  else if (vlNode.getKind() == kind::EXPONENTIAL
1169
66807
           || vlNode.getKind() == kind::SINE || vlNode.getKind() == kind::COSINE
1170
133217
           || vlNode.getKind() == kind::TANGENT)
1171
  {
1172
493
    d_foundNl = true;
1173
  }
1174
1175
  /* Note:
1176
   * Only call markSetup if the VarList is not a singleton.
1177
   * See the comment in setupPolynomail for more.
1178
   */
1179
69368
}
1180
1181
void TheoryArithPrivate::cautiousSetupPolynomial(const Polynomial& p){
1182
  if(p.containsConstant()){
1183
    if(!p.isConstant()){
1184
      Polynomial noConstant = p.getTail();
1185
      if(!isSetup(noConstant.getNode())){
1186
        setupPolynomial(noConstant);
1187
      }
1188
    }
1189
  }else if(!isSetup(p.getNode())){
1190
    setupPolynomial(p);
1191
  }
1192
}
1193
1194
1195
123653
void TheoryArithPrivate::setupPolynomial(const Polynomial& poly) {
1196
123653
  Assert(!poly.containsConstant());
1197
247306
  TNode polyNode = poly.getNode();
1198
123653
  Assert(!isSetup(polyNode));
1199
123653
  Assert(!d_partialModel.hasArithVar(polyNode));
1200
1201
371968
  for(Polynomial::iterator i = poly.begin(), end = poly.end(); i != end; ++i){
1202
496630
    Monomial mono = *i;
1203
248315
    const VarList& vl = mono.getVarList();
1204
248315
    if(!isSetup(vl.getNode())){
1205
63735
      setupVariableList(vl);
1206
    }
1207
  }
1208
1209
123652
  if(polyNode.getKind() == PLUS){
1210
94728
    d_tableauSizeHasBeenModified = true;
1211
1212
189456
    vector<ArithVar> variables;
1213
189456
    vector<Rational> coefficients;
1214
94728
    asVectors(poly, coefficients, variables);
1215
1216
94728
    ArithVar varSlack = requestArithVar(polyNode, true, false);
1217
94728
    d_tableau.addRow(varSlack, coefficients, variables);
1218
94728
    setupBasicValue(varSlack);
1219
94728
    d_linEq.trackRowIndex(d_tableau.basicToRowIndex(varSlack));
1220
1221
    //Add differences to the difference manager
1222
189456
    Polynomial::iterator i = poly.begin(), end = poly.end();
1223
94728
    if(i != end){
1224
189456
      Monomial first = *i;
1225
94728
      ++i;
1226
94728
      if(i != end){
1227
189456
        Monomial second = *i;
1228
94728
        ++i;
1229
94728
        if(i == end){
1230
75526
          if(first.getConstant().isOne() && second.getConstant().getValue() == -1){
1231
129974
            VarList vl0 = first.getVarList();
1232
129974
            VarList vl1 = second.getVarList();
1233
64987
            if(vl0.singleton() && vl1.singleton()){
1234
62665
              d_congruenceManager.addWatchedPair(varSlack, vl0.getNode(), vl1.getNode());
1235
            }
1236
          }
1237
        }
1238
      }
1239
    }
1240
1241
94728
    ++(d_statistics.d_statAuxiliaryVariables);
1242
94728
    markSetup(polyNode);
1243
  }
1244
1245
  /* Note:
1246
   * It is worth documenting that polyNode should only be marked as
1247
   * being setup by this function if it has kind PLUS.
1248
   * Other kinds will be marked as being setup by lower levels of setup
1249
   * specifically setupVariableList.
1250
   */
1251
123652
}
1252
1253
271337
void TheoryArithPrivate::setupAtom(TNode atom) {
1254
271337
  Assert(isRelationOperator(atom.getKind())) << atom;
1255
271337
  Assert(Comparison::isNormalAtom(atom));
1256
271337
  Assert(!isSetup(atom));
1257
271337
  Assert(!d_constraintDatabase.hasLiteral(atom));
1258
1259
542674
  Comparison cmp = Comparison::parseNormalForm(atom);
1260
542674
  Polynomial nvp = cmp.normalizedVariablePart();
1261
271337
  Assert(!nvp.isZero());
1262
1263
271337
  if(!isSetup(nvp.getNode())){
1264
123653
    setupPolynomial(nvp);
1265
  }
1266
1267
271336
  d_constraintDatabase.addLiteral(atom);
1268
1269
271336
  markSetup(atom);
1270
271336
}
1271
1272
816009
void TheoryArithPrivate::preRegisterTerm(TNode n) {
1273
816009
  Debug("arith::preregister") <<"begin arith::preRegisterTerm("<< n <<")"<< endl;
1274
1275
816009
  d_preregisteredNodes.insert(n);
1276
1277
  try {
1278
816009
    if(isRelationOperator(n.getKind())){
1279
423458
      if(!isSetup(n)){
1280
212635
        setupAtom(n);
1281
      }
1282
423457
      ConstraintP c = d_constraintDatabase.lookup(n);
1283
423457
      Assert(c != NullConstraint);
1284
1285
423457
      Debug("arith::preregister") << "setup constraint" << c << endl;
1286
423457
      Assert(!c->canBePropagated());
1287
423457
      c->setPreregistered();
1288
    }
1289
2
  } catch(LogicException& le) {
1290
2
    std::stringstream ss;
1291
1
    ss << le.getMessage() << endl << "The fact in question: " << n << endl;
1292
1
    throw LogicException(ss.str());
1293
  }
1294
1295
816008
  Debug("arith::preregister") << "end arith::preRegisterTerm("<< n <<")" << endl;
1296
816008
}
1297
1298
void TheoryArithPrivate::releaseArithVar(ArithVar v){
1299
  //Assert(d_partialModel.hasNode(v));
1300
1301
  d_constraintDatabase.removeVariable(v);
1302
  d_partialModel.releaseArithVar(v);
1303
}
1304
1305
165094
ArithVar TheoryArithPrivate::requestArithVar(TNode x, bool aux, bool internal){
1306
  //TODO : The VarList trick is good enough?
1307
165094
  Assert(isLeaf(x) || VarList::isMember(x) || x.getKind() == PLUS || internal);
1308
165094
  if (logicInfo().isLinear() && Variable::isDivMember(x))
1309
  {
1310
    stringstream ss;
1311
    ss << "A non-linear fact (involving div/mod/divisibility) was asserted to "
1312
          "arithmetic in a linear logic: "
1313
       << x << std::endl;
1314
    throw LogicException(ss.str());
1315
  }
1316
165094
  Assert(!d_partialModel.hasArithVar(x));
1317
165094
  Assert(x.getType().isReal());  // real or integer
1318
1319
165094
  ArithVar max = d_partialModel.getNumberOfVariables();
1320
165094
  ArithVar varX = d_partialModel.allocate(x, aux);
1321
1322
165094
  bool reclaim =  max >= d_partialModel.getNumberOfVariables();;
1323
1324
165094
  if(!reclaim){
1325
165094
    d_dualSimplex.increaseMax();
1326
1327
165094
    d_tableau.increaseSize();
1328
165094
    d_tableauSizeHasBeenModified = true;
1329
  }
1330
165094
  d_constraintDatabase.addVariable(varX);
1331
1332
330188
  Debug("arith::arithvar") << "@" << getSatContext()->getLevel()
1333
165094
                           << " " << x << " |-> " << varX
1334
165094
                           << "(relaiming " << reclaim << ")" << endl;
1335
1336
165094
  Assert(!d_partialModel.hasUpperBound(varX));
1337
165094
  Assert(!d_partialModel.hasLowerBound(varX));
1338
1339
165094
  return varX;
1340
}
1341
1342
94728
void TheoryArithPrivate::asVectors(const Polynomial& p, std::vector<Rational>& coeffs, std::vector<ArithVar>& variables) {
1343
314118
  for(Polynomial::iterator i = p.begin(), end = p.end(); i != end; ++i){
1344
438780
    const Monomial& mono = *i;
1345
219390
    const Constant& constant = mono.getConstant();
1346
219390
    const VarList& variable = mono.getVarList();
1347
1348
438780
    Node n = variable.getNode();
1349
1350
219390
    Debug("arith::asVectors") << "should be var: " << n << endl;
1351
1352
    // TODO: This VarList::isMember(n) can be stronger
1353
219390
    Assert(isLeaf(n) || VarList::isMember(n));
1354
219390
    Assert(theoryOf(n) != THEORY_ARITH || d_partialModel.hasArithVar(n));
1355
1356
219390
    Assert(d_partialModel.hasArithVar(n));
1357
219390
    ArithVar av = d_partialModel.asArithVar(n);
1358
1359
219390
    coeffs.push_back(constant.getValue());
1360
219390
    variables.push_back(av);
1361
  }
1362
94728
}
1363
1364
/* Requirements:
1365
 * For basic variables the row must have been added to the tableau.
1366
 */
1367
94728
void TheoryArithPrivate::setupBasicValue(ArithVar x){
1368
94728
  Assert(d_tableau.isBasic(x));
1369
  //If the variable is basic, assertions may have already happened and updates
1370
  //may have occured before setting this variable up.
1371
1372
  //This can go away if the tableau creation is done at preregister
1373
  //time instead of register
1374
189456
  DeltaRational safeAssignment = d_linEq.computeRowValue(x, true);
1375
189456
  DeltaRational assignment = d_linEq.computeRowValue(x, false);
1376
94728
  d_partialModel.setAssignment(x,safeAssignment,assignment);
1377
1378
94728
  Debug("arith") << "setupVariable("<<x<<")"<<std::endl;
1379
94728
}
1380
1381
ArithVar TheoryArithPrivate::determineArithVar(const Polynomial& p) const{
1382
  Assert(!p.containsConstant());
1383
  Assert(p.getHead().constantIsPositive());
1384
  TNode n = p.getNode();
1385
  Debug("determineArithVar") << "determineArithVar(" << n << ")" << endl;
1386
  return d_partialModel.asArithVar(n);
1387
}
1388
1389
ArithVar TheoryArithPrivate::determineArithVar(TNode assertion) const{
1390
  Debug("determineArithVar") << "determineArithVar " << assertion << endl;
1391
  Comparison cmp = Comparison::parseNormalForm(assertion);
1392
  Polynomial variablePart = cmp.normalizedVariablePart();
1393
  return determineArithVar(variablePart);
1394
}
1395
1396
1397
bool TheoryArithPrivate::canSafelyAvoidEqualitySetup(TNode equality){
1398
  Assert(equality.getKind() == EQUAL);
1399
  return d_partialModel.hasArithVar(equality[0]);
1400
}
1401
1402
38655
Comparison TheoryArithPrivate::mkIntegerEqualityFromAssignment(ArithVar v){
1403
38655
  const DeltaRational& beta = d_partialModel.getAssignment(v);
1404
1405
38655
  Assert(beta.isIntegral());
1406
77310
  Polynomial betaAsPolynomial = Polynomial::mkPolynomial( Constant::mkConstant(beta.floor()) );
1407
1408
77310
  TNode var = d_partialModel.asNode(v);
1409
77310
  Polynomial varAsPolynomial = Polynomial::parsePolynomial(var);
1410
77310
  return Comparison::mkComparison(EQUAL, varAsPolynomial, betaAsPolynomial);
1411
}
1412
1413
1919
TrustNode TheoryArithPrivate::dioCutting()
1414
{
1415
3838
  context::Context::ScopedPush speculativePush(getSatContext());
1416
  //DO NOT TOUCH THE OUTPUTSTREAM
1417
1418
88146
  for(var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
1419
86227
    ArithVar v = *vi;
1420
86227
    if(isInteger(v)){
1421
142329
      if(d_partialModel.cmpAssignmentUpperBound(v) == 0 ||
1422
56412
         d_partialModel.cmpAssignmentLowerBound(v) == 0){
1423
37336
        if(!d_partialModel.boundsAreEqual(v)){
1424
          // If the bounds are equal this is already in the dioSolver
1425
          //Add v = dr as a speculation.
1426
32178
          Comparison eq = mkIntegerEqualityFromAssignment(v);
1427
16089
          Debug("dio::push") << "dio::push " << v << " " <<  eq.getNode() << endl;
1428
16089
          Assert(!eq.isBoolean());
1429
16089
          d_diosolver.pushInputConstraint(eq, eq.getNode());
1430
          // It does not matter what the explanation of eq is.
1431
          // It cannot be used in a conflict
1432
        }
1433
      }
1434
    }
1435
  }
1436
1437
3838
  SumPair plane = d_diosolver.processEquationsForCut();
1438
1919
  if(plane.isZero()){
1439
460
    return TrustNode::null();
1440
  }else{
1441
2918
    Polynomial p = plane.getPolynomial();
1442
2918
    Polynomial c = Polynomial::mkPolynomial(plane.getConstant() * Constant::mkConstant(-1));
1443
2918
    Integer gcd = p.gcd();
1444
1459
    Assert(p.isIntegral());
1445
1459
    Assert(c.isIntegral());
1446
1459
    Assert(gcd > 1);
1447
1459
    Assert(!gcd.divides(c.asConstant().getNumerator()));
1448
2918
    Comparison leq = Comparison::mkComparison(LEQ, p, c);
1449
2918
    Comparison geq = Comparison::mkComparison(GEQ, p, c);
1450
2918
    Node lemma = NodeManager::currentNM()->mkNode(OR, leq.getNode(), geq.getNode());
1451
2918
    Node rewrittenLemma = Rewriter::rewrite(lemma);
1452
1459
    Debug("arith::dio::ex") << "dioCutting found the plane: " << plane.getNode() << endl;
1453
1459
    Debug("arith::dio::ex") << "resulting in the cut: " << lemma << endl;
1454
1459
    Debug("arith::dio::ex") << "rewritten " << rewrittenLemma << endl;
1455
1459
    Debug("arith::dio") << "dioCutting found the plane: " << plane.getNode() << endl;
1456
1459
    Debug("arith::dio") << "resulting in the cut: " << lemma << endl;
1457
1459
    Debug("arith::dio") << "rewritten " << rewrittenLemma << endl;
1458
1459
    if (proofsEnabled())
1459
    {
1460
206
      NodeManager* nm = NodeManager::currentNM();
1461
412
      Node gt = nm->mkNode(kind::GT, p.getNode(), c.getNode());
1462
412
      Node lt = nm->mkNode(kind::LT, p.getNode(), c.getNode());
1463
1464
412
      Pf pfNotLeq = d_pnm->mkAssume(leq.getNode().negate());
1465
      Pf pfGt =
1466
412
          d_pnm->mkNode(PfRule::MACRO_SR_PRED_TRANSFORM, {pfNotLeq}, {gt});
1467
412
      Pf pfNotGeq = d_pnm->mkAssume(geq.getNode().negate());
1468
      Pf pfLt =
1469
412
          d_pnm->mkNode(PfRule::MACRO_SR_PRED_TRANSFORM, {pfNotGeq}, {lt});
1470
      Pf pfSum =
1471
206
          d_pnm->mkNode(PfRule::MACRO_ARITH_SCALE_SUM_UB,
1472
                        {pfGt, pfLt},
1473
412
                        {nm->mkConst<Rational>(-1), nm->mkConst<Rational>(1)});
1474
206
      Pf pfBot = d_pnm->mkNode(
1475
412
          PfRule::MACRO_SR_PRED_TRANSFORM, {pfSum}, {nm->mkConst<bool>(false)});
1476
206
      std::vector<Node> assumptions = {leq.getNode().negate(),
1477
412
                                       geq.getNode().negate()};
1478
412
      Pf pfNotAndNot = d_pnm->mkScope(pfBot, assumptions);
1479
412
      Pf pfOr = d_pnm->mkNode(PfRule::NOT_AND, {pfNotAndNot}, {});
1480
206
      Pf pfRewritten = d_pnm->mkNode(
1481
412
          PfRule::MACRO_SR_PRED_TRANSFORM, {pfOr}, {rewrittenLemma});
1482
206
      return d_pfGen->mkTrustNode(rewrittenLemma, pfRewritten);
1483
    }
1484
    else
1485
    {
1486
1253
      return TrustNode::mkTrustLemma(rewrittenLemma, nullptr);
1487
    }
1488
  }
1489
}
1490
1491
25332
Node TheoryArithPrivate::callDioSolver(){
1492
47898
  while(!d_constantIntegerVariables.empty()){
1493
22566
    ArithVar v = d_constantIntegerVariables.front();
1494
22566
    d_constantIntegerVariables.pop();
1495
1496
22566
    Debug("arith::dio")  << "callDioSolver " << v << endl;
1497
1498
22566
    Assert(isInteger(v));
1499
22566
    Assert(d_partialModel.boundsAreEqual(v));
1500
1501
22566
    ConstraintP lb = d_partialModel.getLowerBoundConstraint(v);
1502
22566
    ConstraintP ub = d_partialModel.getUpperBoundConstraint(v);
1503
1504
45132
    Node orig = Node::null();
1505
22566
    if(lb->isEquality()){
1506
20720
      orig = Constraint::externalExplainByAssertions({lb});
1507
1846
    }else if(ub->isEquality()){
1508
      orig = Constraint::externalExplainByAssertions({ub});
1509
    }else {
1510
1846
      orig = Constraint::externalExplainByAssertions(ub, lb);
1511
    }
1512
1513
22566
    Assert(d_partialModel.assignmentIsConsistent(v));
1514
1515
45132
    Comparison eq = mkIntegerEqualityFromAssignment(v);
1516
1517
22566
    if(eq.isBoolean()){
1518
      //This can only be a conflict
1519
      Assert(!eq.getNode().getConst<bool>());
1520
1521
      //This should be handled by the normal form earlier in the case of equality
1522
      Assert(orig.getKind() != EQUAL);
1523
      return orig;
1524
    }else{
1525
22566
      Debug("dio::push") << "dio::push " << v << " " << eq.getNode() << " with reason " << orig << endl;
1526
22566
      d_diosolver.pushInputConstraint(eq, orig);
1527
    }
1528
  }
1529
1530
2766
  return d_diosolver.processEquationsForConflict();
1531
}
1532
1533
5896760
ConstraintP TheoryArithPrivate::constraintFromFactQueue(TNode assertion)
1534
{
1535
5896760
  Kind simpleKind = Comparison::comparisonKind(assertion);
1536
5896760
  ConstraintP constraint = d_constraintDatabase.lookup(assertion);
1537
5896760
  if(constraint == NullConstraint){
1538
823895
    Assert(simpleKind == EQUAL || simpleKind == DISTINCT);
1539
823895
    bool isDistinct = simpleKind == DISTINCT;
1540
1637326
    Node eq = (simpleKind == DISTINCT) ? assertion[0] : assertion;
1541
823895
    Assert(!isSetup(eq));
1542
1637326
    Node reEq = Rewriter::rewrite(eq);
1543
823895
    Debug("arith::distinct::const") << "Assertion: " << assertion << std::endl;
1544
823895
    Debug("arith::distinct::const") << "Eq       : " << eq << std::endl;
1545
823895
    Debug("arith::distinct::const") << "reEq     : " << reEq << std::endl;
1546
823895
    if(reEq.getKind() == CONST_BOOLEAN){
1547
10464
      if(reEq.getConst<bool>() == isDistinct){
1548
        // if is (not true), or false
1549
        Assert((reEq.getConst<bool>() && isDistinct)
1550
               || (!reEq.getConst<bool>() && !isDistinct));
1551
        if (proofsEnabled())
1552
        {
1553
          Pf assume = d_pnm->mkAssume(assertion);
1554
          std::vector<Node> assumptions = {assertion};
1555
          Pf pf = d_pnm->mkScope(d_pnm->mkNode(PfRule::MACRO_SR_PRED_TRANSFORM,
1556
                                               {d_pnm->mkAssume(assertion)},
1557
                                               {}),
1558
                                 assumptions);
1559
          raiseBlackBoxConflict(assertion, pf);
1560
        }
1561
        else
1562
        {
1563
          raiseBlackBoxConflict(assertion);
1564
        }
1565
      }
1566
10464
      return NullConstraint;
1567
    }
1568
813431
    Assert(reEq.getKind() != CONST_BOOLEAN);
1569
813431
    if(!isSetup(reEq)){
1570
38329
      setupAtom(reEq);
1571
    }
1572
1626862
    Node reAssertion = isDistinct ? reEq.notNode() : reEq;
1573
813431
    constraint = d_constraintDatabase.lookup(reAssertion);
1574
1575
813431
    if(assertion != reAssertion){
1576
793808
      Debug("arith::nf") << "getting non-nf assertion " << assertion << " |-> " <<  reAssertion << endl;
1577
793808
      Assert(constraint != NullConstraint);
1578
793808
      d_assertionsThatDoNotMatchTheirLiterals.insert(assertion, constraint);
1579
    }
1580
  }
1581
1582
5886296
  Assert(constraint != NullConstraint);
1583
1584
5886296
  if(constraint->assertedToTheTheory()){
1585
    //Do nothing
1586
290852
    return NullConstraint;
1587
  }
1588
5595444
  Assert(!constraint->assertedToTheTheory());
1589
5595444
  bool inConflict = constraint->negationHasProof();
1590
5595444
  constraint->setAssertedToTheTheory(assertion, inConflict);
1591
1592
5595444
  if(!constraint->hasProof()){
1593
4595345
    Debug("arith::constraint") << "marking as constraint as self explaining " << endl;
1594
4595345
    constraint->setAssumption(inConflict);
1595
  } else {
1596
2000198
    Debug("arith::constraint")
1597
1000099
        << "already has proof: "
1598
1000099
        << Constraint::externalExplainByAssertions({constraint});
1599
  }
1600
1601
5595444
  if(Debug.isOn("arith::negatedassumption") && inConflict){
1602
    ConstraintP negation = constraint->getNegation();
1603
    if(Debug.isOn("arith::negatedassumption") && negation->isAssumption()){
1604
      debugPrintFacts();
1605
    }
1606
    Debug("arith::eq") << "negation has proof" << endl;
1607
    Debug("arith::eq") << constraint << endl;
1608
    Debug("arith::eq") << negation << endl;
1609
  }
1610
1611
5595444
  if(inConflict){
1612
3639
    ConstraintP negation = constraint->getNegation();
1613
3639
    if(Debug.isOn("arith::negatedassumption") && negation->isAssumption()){
1614
      debugPrintFacts();
1615
    }
1616
3639
    Debug("arith::eq") << "negation has proof" << endl;
1617
3639
    Debug("arith::eq") << constraint << endl;
1618
3639
    Debug("arith::eq") << negation << endl;
1619
3639
    raiseConflict(negation, InferenceId::ARITH_CONF_FACT_QUEUE);
1620
3639
    return NullConstraint;
1621
  }else{
1622
5591805
    return constraint;
1623
  }
1624
}
1625
1626
5726216
bool TheoryArithPrivate::assertionCases(ConstraintP constraint){
1627
5726216
  Assert(constraint->hasProof());
1628
5726216
  Assert(!constraint->negationHasProof());
1629
1630
5726216
  ArithVar x_i = constraint->getVariable();
1631
1632
5726216
  switch(constraint->getType()){
1633
1924384
  case UpperBound:
1634
1924384
    if(isInteger(x_i) && constraint->isStrictUpperBound()){
1635
1193875
      ConstraintP floorConstraint = constraint->getFloor();
1636
1193875
      if(!floorConstraint->isTrue()){
1637
990364
        bool inConflict = floorConstraint->negationHasProof();
1638
990364
        if (Debug.isOn("arith::intbound")) {
1639
          Debug("arith::intbound") << "literal, before: " << constraint->getLiteral() << std::endl;
1640
          Debug("arith::intbound") << "constraint, after: " << floorConstraint << std::endl;
1641
        }
1642
990364
        floorConstraint->impliedByIntTighten(constraint, inConflict);
1643
990364
        floorConstraint->tryToPropagate();
1644
990364
        if(inConflict){
1645
2792
          raiseConflict(floorConstraint, InferenceId::ARITH_TIGHTEN_FLOOR);
1646
2792
          return true;
1647
        }
1648
      }
1649
1191083
      return AssertUpper(floorConstraint);
1650
    }else{
1651
730509
      return AssertUpper(constraint);
1652
    }
1653
1913569
  case LowerBound:
1654
1913569
    if(isInteger(x_i) && constraint->isStrictLowerBound()){
1655
77151
      ConstraintP ceilingConstraint = constraint->getCeiling();
1656
77151
      if(!ceilingConstraint->isTrue()){
1657
40546
        bool inConflict = ceilingConstraint->negationHasProof();
1658
40546
        if (Debug.isOn("arith::intbound")) {
1659
          Debug("arith::intbound") << "literal, before: " << constraint->getLiteral() << std::endl;
1660
          Debug("arith::intbound") << "constraint, after: " << ceilingConstraint << std::endl;
1661
        }
1662
40546
        ceilingConstraint->impliedByIntTighten(constraint, inConflict);
1663
40546
        ceilingConstraint->tryToPropagate();
1664
40546
        if(inConflict){
1665
37
          raiseConflict(ceilingConstraint, InferenceId::ARITH_TIGHTEN_CEIL);
1666
37
          return true;
1667
        }
1668
      }
1669
77114
      return AssertLower(ceilingConstraint);
1670
    }else{
1671
1836418
      return AssertLower(constraint);
1672
    }
1673
1080291
  case Equality:
1674
1080291
    return AssertEquality(constraint);
1675
807972
  case Disequality:
1676
807972
    return AssertDisequality(constraint);
1677
  default:
1678
    Unreachable();
1679
    return false;
1680
  }
1681
}
1682
/**
1683
 * Looks for through the variables starting at d_nextIntegerCheckVar
1684
 * for the first integer variable that is between its upper and lower bounds
1685
 * that has a non-integer assignment.
1686
 *
1687
 * If assumeBounds is true, skip the check that the variable is in bounds.
1688
 *
1689
 * If there is no such variable, returns ARITHVAR_SENTINEL;
1690
 */
1691
3606851
ArithVar TheoryArithPrivate::nextIntegerViolation(bool assumeBounds) const
1692
{
1693
3606851
  ArithVar numVars = d_partialModel.getNumberOfVariables();
1694
3606851
  ArithVar v = d_nextIntegerCheckVar;
1695
3606851
  if (numVars > 0)
1696
  {
1697
3565961
    const ArithVar rrEnd = d_nextIntegerCheckVar;
1698
649553120
    do
1699
    {
1700
653119081
      if (isIntegerInput(v))
1701
      {
1702
182520053
        if (!d_partialModel.integralAssignment(v))
1703
        {
1704
133029
          if (assumeBounds || d_partialModel.assignmentIsConsistent(v))
1705
          {
1706
133029
            return v;
1707
          }
1708
        }
1709
      }
1710
652986052
      v = (1 + v == numVars) ? 0 : (1 + v);
1711
652986052
    } while (v != rrEnd);
1712
  }
1713
3473822
  return ARITHVAR_SENTINEL;
1714
}
1715
1716
/**
1717
 * Checks the set of integer variables I to see if each variable
1718
 * in I has an integer assignment.
1719
 */
1720
3606851
bool TheoryArithPrivate::hasIntegerModel()
1721
{
1722
3606851
  ArithVar next = nextIntegerViolation(true);
1723
3606851
  if (next != ARITHVAR_SENTINEL)
1724
  {
1725
133029
    d_nextIntegerCheckVar = next;
1726
133029
    if (Debug.isOn("arith::hasIntegerModel"))
1727
    {
1728
      Debug("arith::hasIntegerModel") << "has int model? " << next << endl;
1729
      d_partialModel.printModel(next, Debug("arith::hasIntegerModel"));
1730
    }
1731
133029
    return false;
1732
  }
1733
  else
1734
  {
1735
3473822
    return true;
1736
  }
1737
}
1738
1739
Node flattenAndSort(Node n){
1740
  Kind k = n.getKind();
1741
  switch(k){
1742
  case kind::OR:
1743
  case kind::AND:
1744
  case kind::PLUS:
1745
  case kind::MULT:
1746
    break;
1747
  default:
1748
    return n;
1749
  }
1750
1751
  std::vector<Node> out;
1752
  std::vector<Node> process;
1753
  process.push_back(n);
1754
  while(!process.empty()){
1755
    Node b = process.back();
1756
    process.pop_back();
1757
    if(b.getKind() == k){
1758
      for(Node::iterator i=b.begin(), end=b.end(); i!=end; ++i){
1759
        process.push_back(*i);
1760
      }
1761
    } else {
1762
      out.push_back(b);
1763
    }
1764
  }
1765
  Assert(out.size() >= 2);
1766
  std::sort(out.begin(), out.end());
1767
  return NodeManager::currentNM()->mkNode(k, out);
1768
}
1769
1770
1771
1772
/** Outputs conflicts to the output channel. */
1773
57086
void TheoryArithPrivate::outputConflicts(){
1774
57086
  Debug("arith::conflict") << "outputting conflicts" << std::endl;
1775
57086
  Assert(anyConflict());
1776
  static unsigned int conflicts = 0;
1777
1778
57086
  if(!conflictQueueEmpty()){
1779
54704
    Assert(!d_conflicts.empty());
1780
135266
    for(size_t i = 0, i_end = d_conflicts.size(); i < i_end; ++i){
1781
80562
      const std::pair<ConstraintCP, InferenceId>& conf = d_conflicts[i];
1782
80562
      const ConstraintCP& confConstraint = conf.first;
1783
80562
      bool hasProof = confConstraint->hasProof();
1784
80562
      Assert(confConstraint->inConflict());
1785
80562
      const ConstraintRule& pf = confConstraint->getConstraintRule();
1786
80562
      if (Debug.isOn("arith::conflict"))
1787
      {
1788
        pf.print(std::cout);
1789
        std::cout << std::endl;
1790
      }
1791
80562
      if (Debug.isOn("arith::pf::tree"))
1792
      {
1793
        Debug("arith::pf::tree") << "\n\nTree:\n";
1794
        confConstraint->printProofTree(Debug("arith::pf::tree"));
1795
        confConstraint->getNegation()->printProofTree(Debug("arith::pf::tree"));
1796
      }
1797
1798
161124
      TrustNode trustedConflict = confConstraint->externalExplainConflict();
1799
161124
      Node conflict = trustedConflict.getNode();
1800
1801
80562
      ++conflicts;
1802
161124
      Debug("arith::conflict") << "d_conflicts[" << i << "] " << conflict
1803
80562
                               << " has proof: " << hasProof << endl;
1804
80562
      if(Debug.isOn("arith::normalize::external")){
1805
        conflict = flattenAndSort(conflict);
1806
        Debug("arith::conflict") << "(normalized to) " << conflict << endl;
1807
      }
1808
1809
80562
      if (isProofEnabled())
1810
      {
1811
13027
        outputTrustedConflict(trustedConflict, conf.second);
1812
      }
1813
      else
1814
      {
1815
67535
        outputConflict(conflict, conf.second);
1816
      }
1817
    }
1818
  }
1819
57086
  if(!d_blackBoxConflict.get().isNull()){
1820
4782
    Node bb = d_blackBoxConflict.get();
1821
2391
    ++conflicts;
1822
4782
    Debug("arith::conflict") << "black box conflict" << bb
1823
      //<< "("<<conflicts<<")"
1824
2391
                             << endl;
1825
2391
    if(Debug.isOn("arith::normalize::external")){
1826
      bb = flattenAndSort(bb);
1827
      Debug("arith::conflict") << "(normalized to) " << bb << endl;
1828
    }
1829
2391
    if (isProofEnabled() && d_blackBoxConflictPf.get())
1830
    {
1831
752
      auto confPf = d_blackBoxConflictPf.get();
1832
376
      outputTrustedConflict(d_pfGen->mkTrustNode(bb, confPf, true), InferenceId::ARITH_BLACK_BOX);
1833
    }
1834
    else
1835
    {
1836
2015
      outputConflict(bb, InferenceId::ARITH_BLACK_BOX);
1837
    }
1838
  }
1839
57086
}
1840
1841
71434
bool TheoryArithPrivate::outputTrustedLemma(TrustNode lemma, InferenceId id)
1842
{
1843
71434
  Debug("arith::channel") << "Arith trusted lemma: " << lemma << std::endl;
1844
71434
  return d_containing.d_im.trustedLemma(lemma, id);
1845
}
1846
1847
84902
bool TheoryArithPrivate::outputLemma(TNode lem, InferenceId id) {
1848
84902
  Debug("arith::channel") << "Arith lemma: " << lem << std::endl;
1849
84902
  return d_containing.d_im.lemma(lem, id);
1850
}
1851
1852
13403
void TheoryArithPrivate::outputTrustedConflict(TrustNode conf, InferenceId id)
1853
{
1854
13403
  Debug("arith::channel") << "Arith trusted conflict: " << conf << std::endl;
1855
13403
  d_containing.d_im.trustedConflict(conf, id);
1856
13403
}
1857
1858
69550
void TheoryArithPrivate::outputConflict(TNode lit, InferenceId id) {
1859
69550
  Debug("arith::channel") << "Arith conflict: " << lit << std::endl;
1860
69550
  d_containing.d_im.conflict(lit, id);
1861
69550
}
1862
1863
1511164
void TheoryArithPrivate::outputPropagate(TNode lit) {
1864
1511164
  Debug("arith::channel") << "Arith propagation: " << lit << std::endl;
1865
  // call the propagate lit method of the
1866
1511164
  d_containing.d_im.propagateLit(lit);
1867
1511164
}
1868
1869
void TheoryArithPrivate::outputRestart() {
1870
  Debug("arith::channel") << "Arith restart!" << std::endl;
1871
  (d_containing.d_out)->demandRestart();
1872
}
1873
1874
1769182
bool TheoryArithPrivate::attemptSolveInteger(Theory::Effort effortLevel, bool emmmittedLemmaOrSplit){
1875
1769182
  int level = getSatContext()->getLevel();
1876
3538364
  Debug("approx")
1877
1769182
    << "attemptSolveInteger " << d_qflraStatus
1878
1769182
    << " " << emmmittedLemmaOrSplit
1879
1769182
    << " " << effortLevel
1880
1769182
    << " " << d_lastContextIntegerAttempted
1881
1769182
    << " " << level
1882
3538364
    << " " << hasIntegerModel()
1883
1769182
    << endl;
1884
1885
1769182
  if(d_qflraStatus == Result::UNSAT){ return false; }
1886
1726195
  if(emmmittedLemmaOrSplit){ return false; }
1887
1726195
  if (!options().arith.useApprox)
1888
  {
1889
1726195
    return false;
1890
  }
1891
  if(!ApproximateSimplex::enabled()){ return false; }
1892
1893
  if(Theory::fullEffort(effortLevel)){
1894
    if(hasIntegerModel()){
1895
      return false;
1896
    }else{
1897
      return getSolveIntegerResource();
1898
    }
1899
  }
1900
1901
  if(d_lastContextIntegerAttempted <= 0){
1902
    if(hasIntegerModel()){
1903
      d_lastContextIntegerAttempted = getSatContext()->getLevel();
1904
      return false;
1905
    }else{
1906
      return getSolveIntegerResource();
1907
    }
1908
  }
1909
1910
  if (!options().arith.trySolveIntStandardEffort)
1911
  {
1912
    return false;
1913
  }
1914
1915
  if (d_lastContextIntegerAttempted <= (level >> 2))
1916
  {
1917
    double d = (double)(d_solveIntMaybeHelp + 1)
1918
               / (d_solveIntAttempts + 1 + level * level);
1919
    if (Random::getRandom().pickWithProb(d))
1920
    {
1921
      return getSolveIntegerResource();
1922
    }
1923
  }
1924
  return false;
1925
}
1926
1927
bool TheoryArithPrivate::replayLog(ApproximateSimplex* approx){
1928
  TimerStat::CodeTimer codeTimer(d_statistics.d_replayLogTimer);
1929
1930
  ++d_statistics.d_mipProofsAttempted;
1931
1932
  Assert(d_replayVariables.empty());
1933
  Assert(d_replayConstraints.empty());
1934
1935
  size_t enteringPropN = d_currentPropagationList.size();
1936
  Assert(conflictQueueEmpty());
1937
  TreeLog& tl = getTreeLog();
1938
  //tl.applySelected(); /* set row ids */
1939
1940
  d_replayedLemmas = false;
1941
1942
  /* use the try block for the purpose of pushing the sat context */
1943
  context::Context::ScopedPush speculativePush(getSatContext());
1944
  d_cmEnabled = false;
1945
  std::vector<ConstraintCPVec> res =
1946
      replayLogRec(approx, tl.getRootId(), NullConstraint, 1);
1947
1948
  if(res.empty()){
1949
    ++d_statistics.d_replayAttemptFailed;
1950
  }else{
1951
    unsigned successes = 0;
1952
    for(size_t i =0, N = res.size(); i < N; ++i){
1953
      ConstraintCPVec& vec = res[i];
1954
      Assert(vec.size() >= 2);
1955
      for(size_t j=0, M = vec.size(); j < M; ++j){
1956
        ConstraintCP at_j = vec[j];
1957
        Assert(at_j->isTrue());
1958
        if(!at_j->negationHasProof()){
1959
          successes++;
1960
          vec[j] = vec.back();
1961
          vec.pop_back();
1962
          ConstraintP neg_at_j = at_j->getNegation();
1963
1964
          Debug("approx::replayLog") << "Setting the proof for the replayLog conflict on:" << endl
1965
                                     << "  (" << neg_at_j->isTrue() <<") " << neg_at_j << endl
1966
                                     << "  (" << at_j->isTrue() <<") " << at_j << endl;
1967
          neg_at_j->impliedByIntHole(vec, true);
1968
          raiseConflict(at_j, InferenceId::UNKNOWN);
1969
          break;
1970
        }
1971
      }
1972
    }
1973
    if(successes > 0){
1974
      ++d_statistics.d_mipProofsSuccessful;
1975
    }
1976
  }
1977
1978
  if(d_currentPropagationList.size() > enteringPropN){
1979
    d_currentPropagationList.resize(enteringPropN);
1980
  }
1981
1982
  /* It is not clear what the d_qflraStatus is at this point */
1983
  d_qflraStatus = Result::SAT_UNKNOWN;
1984
1985
  Assert(d_replayVariables.empty());
1986
  Assert(d_replayConstraints.empty());
1987
1988
  return !conflictQueueEmpty();
1989
}
1990
1991
std::pair<ConstraintP, ArithVar> TheoryArithPrivate::replayGetConstraint(const DenseMap<Rational>& lhs, Kind k, const Rational& rhs, bool branch)
1992
{
1993
  ArithVar added = ARITHVAR_SENTINEL;
1994
  Node sum = toSumNode(d_partialModel, lhs);
1995
  if(sum.isNull()){ return make_pair(NullConstraint, added); }
1996
1997
  Debug("approx::constraint") << "replayGetConstraint " << sum
1998
                              << " " << k
1999
                              << " " << rhs
2000
                              << endl;
2001
2002
  Assert(k == kind::LEQ || k == kind::GEQ);
2003
2004
  Node comparison = NodeManager::currentNM()->mkNode(k, sum, mkRationalNode(rhs));
2005
  Node rewritten = Rewriter::rewrite(comparison);
2006
  if(!(Comparison::isNormalAtom(rewritten))){
2007
    return make_pair(NullConstraint, added);
2008
  }
2009
2010
  Comparison cmp = Comparison::parseNormalForm(rewritten);
2011
  if(cmp.isBoolean()){ return make_pair(NullConstraint, added); }
2012
2013
  Polynomial nvp =  cmp.normalizedVariablePart();
2014
  if(nvp.isZero()){ return make_pair(NullConstraint, added); }
2015
2016
  Node norm = nvp.getNode();
2017
2018
  ConstraintType t = Constraint::constraintTypeOfComparison(cmp);
2019
  DeltaRational dr = cmp.normalizedDeltaRational();
2020
2021
  Debug("approx::constraint") << "rewriting " << rewritten << endl
2022
                              << " |-> " << norm << " " << t << " " << dr << endl;
2023
2024
  Assert(!branch || d_partialModel.hasArithVar(norm));
2025
  ArithVar v = ARITHVAR_SENTINEL;
2026
  if(d_partialModel.hasArithVar(norm)){
2027
2028
    v = d_partialModel.asArithVar(norm);
2029
    Debug("approx::constraint") << "replayGetConstraint found "
2030
                                << norm << " |-> " << v << " @ " << getSatContext()->getLevel() << endl;
2031
    Assert(!branch || d_partialModel.isIntegerInput(v));
2032
  }else{
2033
    v = requestArithVar(norm, true, true);
2034
    d_replayVariables.push_back(v);
2035
2036
    added = v;
2037
2038
    Debug("approx::constraint") << "replayGetConstraint adding "
2039
                                << norm << " |-> " << v << " @ " << getSatContext()->getLevel() << endl;
2040
2041
    Polynomial poly = Polynomial::parsePolynomial(norm);
2042
    vector<ArithVar> variables;
2043
    vector<Rational> coefficients;
2044
    asVectors(poly, coefficients, variables);
2045
    d_tableau.addRow(v, coefficients, variables);
2046
    setupBasicValue(v);
2047
    d_linEq.trackRowIndex(d_tableau.basicToRowIndex(v));
2048
  }
2049
  Assert(d_partialModel.hasArithVar(norm));
2050
  Assert(d_partialModel.asArithVar(norm) == v);
2051
  Assert(d_constraintDatabase.variableDatabaseIsSetup(v));
2052
2053
  ConstraintP imp = d_constraintDatabase.getBestImpliedBound(v, t, dr);
2054
  if(imp != NullConstraint){
2055
    if(imp->getValue() == dr){
2056
      Assert(added == ARITHVAR_SENTINEL);
2057
      return make_pair(imp, added);
2058
    }
2059
  }
2060
2061
  ConstraintP newc = d_constraintDatabase.getConstraint(v, t, dr);
2062
  d_replayConstraints.push_back(newc);
2063
  return make_pair(newc, added);
2064
}
2065
2066
std::pair<ConstraintP, ArithVar> TheoryArithPrivate::replayGetConstraint(
2067
    ApproximateSimplex* approx, const NodeLog& nl)
2068
{
2069
  Assert(nl.isBranch());
2070
  Assert(d_lhsTmp.empty());
2071
2072
  ArithVar v = approx->getBranchVar(nl);
2073
  if(v != ARITHVAR_SENTINEL && d_partialModel.isIntegerInput(v)){
2074
    if(d_partialModel.hasNode(v)){
2075
      d_lhsTmp.set(v, Rational(1));
2076
      double dval = nl.branchValue();
2077
      std::optional<Rational> maybe_value =
2078
          ApproximateSimplex::estimateWithCFE(dval);
2079
      if (!maybe_value)
2080
      {
2081
        return make_pair(NullConstraint, ARITHVAR_SENTINEL);
2082
      }
2083
      Rational fl(maybe_value.value().floor());
2084
      pair<ConstraintP, ArithVar> p;
2085
      p = replayGetConstraint(d_lhsTmp, kind::LEQ, fl, true);
2086
      d_lhsTmp.purge();
2087
      return p;
2088
    }
2089
  }
2090
  return make_pair(NullConstraint, ARITHVAR_SENTINEL);
2091
}
2092
2093
std::pair<ConstraintP, ArithVar> TheoryArithPrivate::replayGetConstraint(const CutInfo& ci) {
2094
  Assert(ci.reconstructed());
2095
  const DenseMap<Rational>& lhs = ci.getReconstruction().lhs;
2096
  const Rational& rhs = ci.getReconstruction().rhs;
2097
  Kind k = ci.getKind();
2098
2099
  return replayGetConstraint(lhs, k, rhs, ci.getKlass() == BranchCutKlass);
2100
}
2101
2102
// Node denseVectorToLiteral(const ArithVariables& vars, const DenseVector& dv, Kind k){
2103
//   NodeManager* nm = NodeManager::currentNM();
2104
//   Node sumLhs = toSumNode(vars, dv.lhs);
2105
//   Node ineq = nm->mkNode(k, sumLhs, mkRationalNode(dv.rhs) );
2106
//   Node lit = Rewriter::rewrite(ineq);
2107
//   return lit;
2108
// }
2109
2110
Node toSumNode(const ArithVariables& vars, const DenseMap<Rational>& sum){
2111
  Debug("arith::toSumNode") << "toSumNode() begin" << endl;
2112
  NodeBuilder nb(kind::PLUS);
2113
  NodeManager* nm = NodeManager::currentNM();
2114
  DenseMap<Rational>::const_iterator iter, end;
2115
  iter = sum.begin(), end = sum.end();
2116
  for(; iter != end; ++iter){
2117
    ArithVar x = *iter;
2118
    if(!vars.hasNode(x)){ return Node::null(); }
2119
    Node xNode = vars.asNode(x);
2120
    const Rational& q = sum[x];
2121
    Node mult = nm->mkNode(kind::MULT, mkRationalNode(q), xNode);
2122
    Debug("arith::toSumNode") << "toSumNode() " << x << " " << mult << endl;
2123
    nb << mult;
2124
  }
2125
  Debug("arith::toSumNode") << "toSumNode() end" << endl;
2126
  return safeConstructNary(nb);
2127
}
2128
2129
ConstraintCP TheoryArithPrivate::vectorToIntHoleConflict(const ConstraintCPVec& conflict){
2130
  Assert(conflict.size() >= 2);
2131
  ConstraintCPVec exp(conflict.begin(), conflict.end()-1);
2132
  ConstraintCP back = conflict.back();
2133
  Assert(back->hasProof());
2134
  ConstraintP negBack = back->getNegation();
2135
  // This can select negBack multiple times so we need to test if negBack has a proof.
2136
  if(negBack->hasProof()){
2137
    // back is in conflict already
2138
  } else {
2139
    negBack->impliedByIntHole(exp, true);
2140
  }
2141
2142
  return back;
2143
}
2144
2145
void TheoryArithPrivate::intHoleConflictToVector(ConstraintCP conflicting, ConstraintCPVec& conflict){
2146
  ConstraintCP negConflicting = conflicting->getNegation();
2147
  Assert(conflicting->hasProof());
2148
  Assert(negConflicting->hasProof());
2149
2150
  conflict.push_back(conflicting);
2151
  conflict.push_back(negConflicting);
2152
2153
  Constraint::assertionFringe(conflict);
2154
}
2155
2156
void TheoryArithPrivate::tryBranchCut(ApproximateSimplex* approx, int nid, BranchCutInfo& bci){
2157
  Assert(conflictQueueEmpty());
2158
  std::vector< ConstraintCPVec > conflicts;
2159
2160
  approx->tryCut(nid, bci);
2161
  Debug("approx::branch") << "tryBranchCut" << bci << endl;
2162
  Assert(bci.reconstructed());
2163
  Assert(!bci.proven());
2164
  pair<ConstraintP, ArithVar> p = replayGetConstraint(bci);
2165
  Assert(p.second == ARITHVAR_SENTINEL);
2166
  ConstraintP bc = p.first;
2167
  Assert(bc != NullConstraint);
2168
  if(bc->hasProof()){
2169
    return;
2170
  }
2171
2172
  ConstraintP bcneg = bc->getNegation();
2173
  {
2174
    context::Context::ScopedPush speculativePush(getSatContext());
2175
    replayAssert(bcneg);
2176
    if(conflictQueueEmpty()){
2177
      TimerStat::CodeTimer codeTimer(d_statistics.d_replaySimplexTimer);
2178
2179
      //test for linear feasibility
2180
      d_partialModel.stopQueueingBoundCounts();
2181
      UpdateTrackingCallback utcb(&d_linEq);
2182
      d_partialModel.processBoundsQueue(utcb);
2183
      d_linEq.startTrackingBoundCounts();
2184
2185
      SimplexDecisionProcedure& simplex = selectSimplex(true);
2186
      simplex.findModel(false);
2187
      // Can change d_qflraStatus
2188
2189
      d_linEq.stopTrackingBoundCounts();
2190
      d_partialModel.startQueueingBoundCounts();
2191
    }
2192
    for(size_t i = 0, N = d_conflicts.size(); i < N; ++i){
2193
2194
      conflicts.push_back(ConstraintCPVec());
2195
      intHoleConflictToVector(d_conflicts[i].first, conflicts.back());
2196
      Constraint::assertionFringe(conflicts.back());
2197
2198
      // ConstraintCP conflicting = d_conflicts[i];
2199
      // ConstraintCP negConflicting = conflicting->getNegation();
2200
      // Assert(conflicting->hasProof());
2201
      // Assert(negConflicting->hasProof());
2202
2203
      // conflicts.push_back(ConstraintCPVec());
2204
      // ConstraintCPVec& back = conflicts.back();
2205
      // back.push_back(conflicting);
2206
      // back.push_back(negConflicting);
2207
2208
      // // remove the floor/ceiling contraint implied by bcneg
2209
      // Constraint::assertionFringe(back);
2210
    }
2211
2212
    if(Debug.isOn("approx::branch")){
2213
      if(d_conflicts.empty()){
2214
        entireStateIsConsistent("branchfailure");
2215
      }
2216
    }
2217
  }
2218
2219
  Debug("approx::branch") << "branch constraint " << bc << endl;
2220
  for(size_t i = 0, N = conflicts.size(); i < N; ++i){
2221
    ConstraintCPVec& conf = conflicts[i];
2222
2223
    // make sure to be working on the assertion fringe!
2224
    if(!contains(conf, bcneg)){
2225
      Debug("approx::branch") << "reraise " << conf  << endl;
2226
      ConstraintCP conflicting = vectorToIntHoleConflict(conf);
2227
      raiseConflict(conflicting, InferenceId::UNKNOWN);
2228
    }else if(!bci.proven()){
2229
      drop(conf, bcneg);
2230
      bci.setExplanation(conf);
2231
      Debug("approx::branch") << "dropped " << bci  << endl;
2232
    }
2233
  }
2234
}
2235
2236
void TheoryArithPrivate::replayAssert(ConstraintP c) {
2237
  if(!c->assertedToTheTheory()){
2238
    bool inConflict = c->negationHasProof();
2239
    if(!c->hasProof()){
2240
      c->setInternalAssumption(inConflict);
2241
      Debug("approx::replayAssert") << "replayAssert " << c << " set internal" << endl;
2242
    }else{
2243
      Debug("approx::replayAssert") << "replayAssert " << c << " has explanation" << endl;
2244
    }
2245
    Debug("approx::replayAssert") << "replayAssertion " << c << endl;
2246
    if(inConflict){
2247
      raiseConflict(c, InferenceId::UNKNOWN);
2248
    }else{
2249
      assertionCases(c);
2250
    }
2251
  }else{
2252
    Debug("approx::replayAssert")
2253
        << "replayAssert " << c << " already asserted" << endl;
2254
  }
2255
}
2256
2257
2258
void TheoryArithPrivate::resolveOutPropagated(std::vector<ConstraintCPVec>& confs, const std::set<ConstraintCP>& propagated) const {
2259
  Debug("arith::resolveOutPropagated")
2260
    << "starting resolveOutPropagated() " << confs.size() << endl;
2261
  for(size_t i =0, N = confs.size(); i < N; ++i){
2262
    ConstraintCPVec& conf = confs[i];
2263
    size_t orig = conf.size();
2264
    Constraint::assertionFringe(conf);
2265
    Debug("arith::resolveOutPropagated")
2266
      << "  conf["<<i<<"] " << orig << " to " << conf.size() << endl;
2267
  }
2268
  Debug("arith::resolveOutPropagated")
2269
    << "ending resolveOutPropagated() " << confs.size() << endl;
2270
}
2271
2272
struct SizeOrd {
2273
  bool operator()(const ConstraintCPVec& a, const ConstraintCPVec& b) const{
2274
    return a.size() < b.size();
2275
  }
2276
};
2277
2278
void TheoryArithPrivate::subsumption(
2279
    std::vector<ConstraintCPVec> &confs) const {
2280
  int checks CVC5_UNUSED = 0;
2281
  int subsumed CVC5_UNUSED = 0;
2282
2283
  for (size_t i = 0, N = confs.size(); i < N; ++i) {
2284
    ConstraintCPVec &conf = confs[i];
2285
    std::sort(conf.begin(), conf.end());
2286
  }
2287
2288
  std::sort(confs.begin(), confs.end(), SizeOrd());
2289
  for (size_t i = 0; i < confs.size(); i++) {
2290
    // i is not subsumed
2291
    for (size_t j = i + 1; j < confs.size();) {
2292
      ConstraintCPVec& a = confs[i];
2293
      ConstraintCPVec& b = confs[j];
2294
      checks++;
2295
      bool subsumes = std::includes(a.begin(), a.end(), b.begin(), b.end());
2296
      if (subsumes) {
2297
        ConstraintCPVec& back = confs.back();
2298
        b.swap(back);
2299
        confs.pop_back();
2300
        subsumed++;
2301
      } else {
2302
        j++;
2303
      }
2304
    }
2305
  }
2306
  Debug("arith::subsumption") << "subsumed " << subsumed << "/" << checks
2307
                              << endl;
2308
}
2309
2310
std::vector<ConstraintCPVec> TheoryArithPrivate::replayLogRec(ApproximateSimplex* approx, int nid, ConstraintP bc, int depth){
2311
  ++(d_statistics.d_replayLogRecCount);
2312
  Debug("approx::replayLogRec") << "replayLogRec()" << std::endl;
2313
2314
  size_t rpvars_size = d_replayVariables.size();
2315
  size_t rpcons_size = d_replayConstraints.size();
2316
  std::vector<ConstraintCPVec> res;
2317
2318
  { /* create a block for the purpose of pushing the sat context */
2319
    context::Context::ScopedPush speculativePush(getSatContext());
2320
    Assert(!anyConflict());
2321
    Assert(conflictQueueEmpty());
2322
    set<ConstraintCP> propagated;
2323
2324
    TreeLog& tl = getTreeLog();
2325
2326
    if(bc != NullConstraint){
2327
      replayAssert(bc);
2328
    }
2329
2330
    const NodeLog& nl = tl.getNode(nid);
2331
    NodeLog::const_iterator iter = nl.begin(), end = nl.end();
2332
    for(; conflictQueueEmpty() && iter != end; ++iter){
2333
      CutInfo* ci = *iter;
2334
      bool reject = false;
2335
      //cout << "  trying " << *ci << endl;
2336
      if(ci->getKlass() == RowsDeletedKlass){
2337
        RowsDeleted* rd = dynamic_cast<RowsDeleted*>(ci);
2338
2339
        tl.applyRowsDeleted(nid, *rd);
2340
        // The previous line modifies nl
2341
2342
        ++d_statistics.d_applyRowsDeleted;
2343
      }else if(ci->getKlass() == BranchCutKlass){
2344
        BranchCutInfo* bci = dynamic_cast<BranchCutInfo*>(ci);
2345
        Assert(bci != NULL);
2346
        tryBranchCut(approx, nid, *bci);
2347
2348
        ++d_statistics.d_branchCutsAttempted;
2349
        if(!(conflictQueueEmpty() || ci->reconstructed())){
2350
          ++d_statistics.d_numBranchesFailed;
2351
        }
2352
      }else{
2353
        approx->tryCut(nid, *ci);
2354
        if(ci->getKlass() == GmiCutKlass){
2355
          ++d_statistics.d_gmiCutsAttempted;
2356
        }else if(ci->getKlass() == MirCutKlass){
2357
          ++d_statistics.d_mirCutsAttempted;
2358
        }
2359
2360
        if(ci->reconstructed() && ci->proven()){
2361
          const DenseMap<Rational>& row = ci->getReconstruction().lhs;
2362
          reject = !complexityBelow(row, options().arith.replayRejectCutSize);
2363
        }
2364
      }
2365
      if(conflictQueueEmpty()){
2366
        if(reject){
2367
          ++d_statistics.d_cutsRejectedDuringReplay;
2368
        }else if(ci->reconstructed()){
2369
          // success
2370
          ++d_statistics.d_cutsReconstructed;
2371
2372
          pair<ConstraintP, ArithVar> p = replayGetConstraint(*ci);
2373
          if(p.second != ARITHVAR_SENTINEL){
2374
            Assert(ci->getRowId() >= 1);
2375
            tl.mapRowId(nl.getNodeId(), ci->getRowId(), p.second);
2376
          }
2377
          ConstraintP con = p.first;
2378
          if(Debug.isOn("approx::replayLogRec")){
2379
            Debug("approx::replayLogRec") << "cut was remade " << con << " " << *ci << endl;
2380
          }
2381
2382
          if(ci->proven()){
2383
            ++d_statistics.d_cutsProven;
2384
2385
            const ConstraintCPVec& exp = ci->getExplanation();
2386
            // success
2387
            if(con->isTrue()){
2388
              Debug("approx::replayLogRec") << "not asserted?" << endl;
2389
            }else if(!con->negationHasProof()){
2390
              con->impliedByIntHole(exp, false);
2391
              replayAssert(con);
2392
              Debug("approx::replayLogRec") << "cut prop" << endl;
2393
            }else {
2394
              con->impliedByIntHole(exp, true);
2395
              Debug("approx::replayLogRec") << "cut into conflict " << con << endl;
2396
              raiseConflict(con, InferenceId::UNKNOWN);
2397
            }
2398
          }else{
2399
            ++d_statistics.d_cutsProofFailed;
2400
            Debug("approx::replayLogRec") << "failed to get proof " << *ci << endl;
2401
          }
2402
        }else if(ci->getKlass() != RowsDeletedKlass){
2403
          ++d_statistics.d_cutsReconstructionFailed;
2404
        }
2405
      }
2406
    }
2407
2408
    /* check if the system is feasible under with the cuts */
2409
    if(conflictQueueEmpty()){
2410
      Assert(options().arith.replayEarlyCloseDepths >= 1);
2411
      if (!nl.isBranch() || depth % options().arith.replayEarlyCloseDepths == 0)
2412
      {
2413
        TimerStat::CodeTimer codeTimer(d_statistics.d_replaySimplexTimer);
2414
        //test for linear feasibility
2415
        d_partialModel.stopQueueingBoundCounts();
2416
        UpdateTrackingCallback utcb(&d_linEq);
2417
        d_partialModel.processBoundsQueue(utcb);
2418
        d_linEq.startTrackingBoundCounts();
2419
2420
        SimplexDecisionProcedure& simplex = selectSimplex(true);
2421
        simplex.findModel(false);
2422
        // can change d_qflraStatus
2423
2424
        d_linEq.stopTrackingBoundCounts();
2425
        d_partialModel.startQueueingBoundCounts();
2426
      }
2427
    }else{
2428
      ++d_statistics.d_replayLogRecConflictEscalation;
2429
    }
2430
2431
    if(!conflictQueueEmpty()){
2432
      /* if a conflict has been found stop */
2433
      for(size_t i = 0, N = d_conflicts.size(); i < N; ++i){
2434
        res.push_back(ConstraintCPVec());
2435
        intHoleConflictToVector(d_conflicts[i].first, res.back());
2436
      }
2437
      ++d_statistics.d_replayLogRecEarlyExit;
2438
    }else if(nl.isBranch()){
2439
      /* if it is a branch try the branch */
2440
      pair<ConstraintP, ArithVar> p = replayGetConstraint(approx, nl);
2441
      Assert(p.second == ARITHVAR_SENTINEL);
2442
      ConstraintP dnc = p.first;
2443
      if(dnc != NullConstraint){
2444
        ConstraintP upc = dnc->getNegation();
2445
2446
        int dnid = nl.getDownId();
2447
        int upid = nl.getUpId();
2448
2449
        NodeLog& dnlog = tl.getNode(dnid);
2450
        NodeLog& uplog = tl.getNode(upid);
2451
        dnlog.copyParentRowIds();
2452
        uplog.copyParentRowIds();
2453
2454
        std::vector<ConstraintCPVec> dnres;
2455
        std::vector<ConstraintCPVec> upres;
2456
        std::vector<size_t> containsdn;
2457
        std::vector<size_t> containsup;
2458
        if(res.empty()){
2459
          dnres = replayLogRec(approx, dnid, dnc, depth+1);
2460
          for(size_t i = 0, N = dnres.size(); i < N; ++i){
2461
            ConstraintCPVec& conf = dnres[i];
2462
            if(contains(conf, dnc)){
2463
              containsdn.push_back(i);
2464
            }else{
2465
              res.push_back(conf);
2466
            }
2467
          }
2468
        }else{
2469
          Debug("approx::replayLogRec") << "replayLogRec() skipping" << dnlog << std::endl;
2470
          ++d_statistics.d_replayBranchSkips;
2471
        }
2472
2473
        if(res.empty()){
2474
          upres = replayLogRec(approx, upid, upc, depth+1);
2475
2476
          for(size_t i = 0, N = upres.size(); i < N; ++i){
2477
            ConstraintCPVec& conf = upres[i];
2478
            if(contains(conf, upc)){
2479
              containsup.push_back(i);
2480
            }else{
2481
              res.push_back(conf);
2482
            }
2483
          }
2484
        }else{
2485
          Debug("approx::replayLogRec") << "replayLogRec() skipping" << uplog << std::endl;
2486
          ++d_statistics.d_replayBranchSkips;
2487
        }
2488
2489
        if(res.empty()){
2490
          for(size_t i = 0, N = containsdn.size(); i < N; ++i){
2491
            ConstraintCPVec& dnconf = dnres[containsdn[i]];
2492
            for(size_t j = 0, M = containsup.size(); j < M; ++j){
2493
              ConstraintCPVec& upconf = upres[containsup[j]];
2494
2495
              res.push_back(ConstraintCPVec());
2496
              ConstraintCPVec& back = res.back();
2497
              resolve(back, dnc, dnconf, upconf);
2498
            }
2499
          }
2500
          if(res.size() >= 2u){
2501
            subsumption(res);
2502
2503
            if(res.size() > 100u){
2504
              res.resize(100u);
2505
            }
2506
          }
2507
        }else{
2508
          Debug("approx::replayLogRec") << "replayLogRec() skipping resolving" << nl << std::endl;
2509
        }
2510
        Debug("approx::replayLogRec") << "found #"<<res.size()<<" conflicts on branch " << nid << endl;
2511
        if(res.empty()){
2512
          ++d_statistics.d_replayBranchCloseFailures;
2513
        }
2514
2515
      }else{
2516
        Debug("approx::replayLogRec") << "failed to make a branch " << nid << endl;
2517
      }
2518
    }else{
2519
      ++d_statistics.d_replayLeafCloseFailures;
2520
      Debug("approx::replayLogRec") << "failed on node " << nid << endl;
2521
      Assert(res.empty());
2522
    }
2523
    resolveOutPropagated(res, propagated);
2524
    Debug("approx::replayLogRec") << "replayLogRec() ending" << std::endl;
2525
2526
    if (options().arith.replayFailureLemma)
2527
    {
2528
      // must be done inside the sat context to get things
2529
      // propagated at this level
2530
      if(res.empty() && nid == getTreeLog().getRootId()){
2531
        Assert(!d_replayedLemmas);
2532
        d_replayedLemmas = replayLemmas(approx);
2533
        Assert(d_acTmp.empty());
2534
        while(!d_approxCuts.empty()){
2535
          TrustNode lem = d_approxCuts.front();
2536
          d_approxCuts.pop();
2537
          d_acTmp.push_back(lem);
2538
        }
2539
      }
2540
    }
2541
  } /* pop the sat context */
2542
2543
  /* move into the current context. */
2544
  while(!d_acTmp.empty()){
2545
    TrustNode lem = d_acTmp.back();
2546
    d_acTmp.pop_back();
2547
    d_approxCuts.push_back(lem);
2548
  }
2549
  Assert(d_acTmp.empty());
2550
2551
  /* Garbage collect the constraints from this call */
2552
  while(d_replayConstraints.size() > rpcons_size){
2553
    ConstraintP c = d_replayConstraints.back();
2554
    d_replayConstraints.pop_back();
2555
    d_constraintDatabase.deleteConstraintAndNegation(c);
2556
  }
2557
2558
  /* Garbage collect the ArithVars made by this call */
2559
  if(d_replayVariables.size() > rpvars_size){
2560
    d_partialModel.stopQueueingBoundCounts();
2561
    UpdateTrackingCallback utcb(&d_linEq);
2562
    d_partialModel.processBoundsQueue(utcb);
2563
    d_linEq.startTrackingBoundCounts();
2564
    while(d_replayVariables.size() > rpvars_size){
2565
      ArithVar v = d_replayVariables.back();
2566
      d_replayVariables.pop_back();
2567
      Assert(d_partialModel.canBeReleased(v));
2568
      if(!d_tableau.isBasic(v)){
2569
        /* if it is not basic make it basic. */
2570
        ArithVar b = ARITHVAR_SENTINEL;
2571
        for(Tableau::ColIterator ci = d_tableau.colIterator(v); !ci.atEnd(); ++ci){
2572
          const Tableau::Entry& e = *ci;
2573
          b = d_tableau.rowIndexToBasic(e.getRowIndex());
2574
          break;
2575
        }
2576
        Assert(b != ARITHVAR_SENTINEL);
2577
        DeltaRational cp = d_partialModel.getAssignment(b);
2578
        if(d_partialModel.cmpAssignmentLowerBound(b) < 0){
2579
          cp = d_partialModel.getLowerBound(b);
2580
        }else if(d_partialModel.cmpAssignmentUpperBound(b) > 0){
2581
          cp = d_partialModel.getUpperBound(b);
2582
        }
2583
        d_linEq.pivotAndUpdate(b, v, cp);
2584
      }
2585
      Assert(d_tableau.isBasic(v));
2586
      d_linEq.stopTrackingRowIndex(d_tableau.basicToRowIndex(v));
2587
      d_tableau.removeBasicRow(v);
2588
2589
      releaseArithVar(v);
2590
      Debug("approx::vars") << "releasing " << v << endl;
2591
    }
2592
    d_linEq.stopTrackingBoundCounts();
2593
    d_partialModel.startQueueingBoundCounts();
2594
    d_partialModel.attemptToReclaimReleased();
2595
  }
2596
  return res;
2597
}
2598
2599
TreeLog& TheoryArithPrivate::getTreeLog(){
2600
  if(d_treeLog == NULL){
2601
    d_treeLog = new TreeLog();
2602
  }
2603
  return *d_treeLog;
2604
}
2605
2606
ApproximateStatistics& TheoryArithPrivate::getApproxStats(){
2607
  if(d_approxStats == NULL){
2608
    d_approxStats = new ApproximateStatistics();
2609
  }
2610
  return *d_approxStats;
2611
}
2612
2613
Node TheoryArithPrivate::branchToNode(ApproximateSimplex* approx,
2614
                                      const NodeLog& bn) const
2615
{
2616
  Assert(bn.isBranch());
2617
  ArithVar v = approx->getBranchVar(bn);
2618
  if(v != ARITHVAR_SENTINEL && d_partialModel.isIntegerInput(v)){
2619
    if(d_partialModel.hasNode(v)){
2620
      Node n = d_partialModel.asNode(v);
2621
      double dval = bn.branchValue();
2622
      std::optional<Rational> maybe_value =
2623
          ApproximateSimplex::estimateWithCFE(dval);
2624
      if (!maybe_value)
2625
      {
2626
        return Node::null();
2627
      }
2628
      Rational fl(maybe_value.value().floor());
2629
      NodeManager* nm = NodeManager::currentNM();
2630
      Node leq = nm->mkNode(kind::LEQ, n, mkRationalNode(fl));
2631
      Node norm = Rewriter::rewrite(leq);
2632
      return norm;
2633
    }
2634
  }
2635
  return Node::null();
2636
}
2637
2638
Node TheoryArithPrivate::cutToLiteral(ApproximateSimplex* approx, const CutInfo& ci) const{
2639
  Assert(ci.reconstructed());
2640
2641
  const DenseMap<Rational>& lhs = ci.getReconstruction().lhs;
2642
  Node sum = toSumNode(d_partialModel, lhs);
2643
  if(!sum.isNull()){
2644
    Kind k = ci.getKind();
2645
    Assert(k == kind::LEQ || k == kind::GEQ);
2646
    Node rhs = mkRationalNode(ci.getReconstruction().rhs);
2647
2648
    NodeManager* nm = NodeManager::currentNM();
2649
    Node ineq = nm->mkNode(k, sum, rhs);
2650
    return Rewriter::rewrite(ineq);
2651
  }
2652
  return Node::null();
2653
}
2654
2655
bool TheoryArithPrivate::replayLemmas(ApproximateSimplex* approx){
2656
    ++(d_statistics.d_mipReplayLemmaCalls);
2657
    bool anythingnew = false;
2658
2659
    TreeLog& tl = getTreeLog();
2660
    NodeLog& root = tl.getRootNode();
2661
    root.applySelected(); /* set row ids */
2662
2663
    vector<const CutInfo*> cuts = approx->getValidCuts(root);
2664
    for(size_t i =0, N =cuts.size(); i < N; ++i){
2665
      const CutInfo* cut = cuts[i];
2666
      Assert(cut->reconstructed());
2667
      Assert(cut->proven());
2668
2669
      const DenseMap<Rational>& row =  cut->getReconstruction().lhs;
2670
      if (!complexityBelow(row, options().arith.lemmaRejectCutSize))
2671
      {
2672
        ++(d_statistics.d_cutsRejectedDuringLemmas);
2673
        continue;
2674
      }
2675
2676
      Node cutConstraint = cutToLiteral(approx, *cut);
2677
      if(!cutConstraint.isNull()){
2678
        const ConstraintCPVec& exp = cut->getExplanation();
2679
        Node asLemma = Constraint::externalExplainByAssertions(exp);
2680
2681
        Node implied = Rewriter::rewrite(cutConstraint);
2682
        anythingnew = anythingnew || !isSatLiteral(implied);
2683
2684
        Node implication = asLemma.impNode(implied);
2685
        // DO NOT CALL OUTPUT LEMMA!
2686
        // TODO (project #37): justify
2687
        d_approxCuts.push_back(TrustNode::mkTrustLemma(implication, nullptr));
2688
        Debug("approx::lemmas") << "cut["<<i<<"] " << implication << endl;
2689
        ++(d_statistics.d_mipExternalCuts);
2690
      }
2691
    }
2692
    if(root.isBranch()){
2693
      Node lit = branchToNode(approx, root);
2694
      if(!lit.isNull()){
2695
        anythingnew = anythingnew || !isSatLiteral(lit);
2696
        Node branch = lit.orNode(lit.notNode());
2697
        if (proofsEnabled())
2698
        {
2699
          d_pfGen->mkTrustNode(branch, PfRule::SPLIT, {}, {lit});
2700
        }
2701
        else
2702
        {
2703
          d_approxCuts.push_back(TrustNode::mkTrustLemma(branch, nullptr));
2704
        }
2705
        ++(d_statistics.d_mipExternalBranch);
2706
        Debug("approx::lemmas") << "branching "<< root <<" as " << branch << endl;
2707
      }
2708
    }
2709
    return anythingnew;
2710
}
2711
2712
void TheoryArithPrivate::turnOffApproxFor(int32_t rounds){
2713
  d_attemptSolveIntTurnedOff = d_attemptSolveIntTurnedOff + rounds;
2714
  ++(d_statistics.d_approxDisabled);
2715
}
2716
2717
1707941
bool TheoryArithPrivate::safeToCallApprox() const{
2718
1707941
  unsigned numRows = 0;
2719
1707941
  unsigned numCols = 0;
2720
1707941
  var_iterator vi = var_begin(), vi_end = var_end();
2721
  // Assign each variable to a row and column variable as it appears in the input
2722
28866779
  for(; vi != vi_end && !(numRows > 0 && numCols > 0); ++vi){
2723
13579419
    ArithVar v = *vi;
2724
2725
13579419
    if(d_partialModel.isAuxiliary(v)){
2726
1690652
      ++numRows;
2727
    }else{
2728
11888767
      ++numCols;
2729
    }
2730
  }
2731
1707941
  return (numRows > 0 && numCols > 0);
2732
}
2733
2734
// solve()
2735
//   res = solveRealRelaxation(effortLevel);
2736
//   switch(res){
2737
//   case LinFeas:
2738
//   case LinInfeas:
2739
//     return replay()
2740
//   case Unknown:
2741
//   case Error
2742
//     if()
2743
void TheoryArithPrivate::solveInteger(Theory::Effort effortLevel){
2744
  if(!safeToCallApprox()) { return; }
2745
2746
  Assert(safeToCallApprox());
2747
  TimerStat::CodeTimer codeTimer0(d_statistics.d_solveIntTimer);
2748
2749
  ++(d_statistics.d_solveIntCalls);
2750
  d_statistics.d_inSolveInteger = 1;
2751
2752
  if(!Theory::fullEffort(effortLevel)){
2753
    d_solveIntAttempts++;
2754
    ++(d_statistics.d_solveStandardEffort);
2755
  }
2756
2757
  // if integers are attempted,
2758
  Assert(options().arith.useApprox);
2759
  Assert(ApproximateSimplex::enabled());
2760
2761
  int level = getSatContext()->getLevel();
2762
  d_lastContextIntegerAttempted = level;
2763
2764
2765
  static const int32_t mipLimit = 200000;
2766
2767
  TreeLog& tl = getTreeLog();
2768
  ApproximateStatistics& stats = getApproxStats();
2769
  ApproximateSimplex* approx =
2770
    ApproximateSimplex::mkApproximateSimplexSolver(d_partialModel, tl, stats);
2771
2772
    approx->setPivotLimit(mipLimit);
2773
    if(!d_guessedCoeffSet){
2774
      d_guessedCoeffs = approx->heuristicOptCoeffs();
2775
      d_guessedCoeffSet = true;
2776
    }
2777
    if(!d_guessedCoeffs.empty()){
2778
      approx->setOptCoeffs(d_guessedCoeffs);
2779
    }
2780
    static const int32_t depthForLikelyInfeasible = 10;
2781
    int maxDepthPass1 = d_likelyIntegerInfeasible
2782
                            ? depthForLikelyInfeasible
2783
                            : options().arith.maxApproxDepth;
2784
    approx->setBranchingDepth(maxDepthPass1);
2785
    approx->setBranchOnVariableLimit(100);
2786
    LinResult relaxRes = approx->solveRelaxation();
2787
    if( relaxRes == LinFeasible ){
2788
      MipResult mipRes = MipUnknown;
2789
      {
2790
        TimerStat::CodeTimer codeTimer1(d_statistics.d_mipTimer);
2791
        mipRes = approx->solveMIP(false);
2792
      }
2793
2794
      Debug("arith::solveInteger") << "mipRes " << mipRes << endl;
2795
      switch(mipRes) {
2796
      case MipBingo:
2797
        // attempt the solution
2798
        {
2799
          ++(d_statistics.d_solveIntModelsAttempts);
2800
2801
          d_partialModel.stopQueueingBoundCounts();
2802
          UpdateTrackingCallback utcb(&d_linEq);
2803
          d_partialModel.processBoundsQueue(utcb);
2804
          d_linEq.startTrackingBoundCounts();
2805
2806
          ApproximateSimplex::Solution mipSolution;
2807
          mipSolution = approx->extractMIP();
2808
          importSolution(mipSolution);
2809
          solveRelaxationOrPanic(effortLevel);
2810
2811
          if (d_qflraStatus == Result::SAT)
2812
          {
2813
            if (!anyConflict())
2814
            {
2815
              if (ARITHVAR_SENTINEL == nextIntegerViolation(false))
2816
              {
2817
                ++(d_statistics.d_solveIntModelsSuccessful);
2818
              }
2819
            }
2820
          }
2821
2822
          // shutdown simplex
2823
          d_linEq.stopTrackingBoundCounts();
2824
          d_partialModel.startQueueingBoundCounts();
2825
        }
2826
        break;
2827
      case MipClosed:
2828
        /* All integer branches closed */
2829
        approx->setPivotLimit(2*mipLimit);
2830
        {
2831
          TimerStat::CodeTimer codeTimer2(d_statistics.d_mipTimer);
2832
          mipRes = approx->solveMIP(true);
2833
        }
2834
2835
        if(mipRes == MipClosed){
2836
          d_likelyIntegerInfeasible = true;
2837
          replayLog(approx);
2838
          AlwaysAssert(anyConflict() || d_qflraStatus != Result::SAT);
2839
2840
          if (!anyConflict())
2841
          {
2842
            solveRealRelaxation(effortLevel);
2843
          }
2844
        }
2845
        if(!(anyConflict() || !d_approxCuts.empty())){
2846
          turnOffApproxFor(options().arith.replayNumericFailurePenalty);
2847
        }
2848
        break;
2849
      case BranchesExhausted:
2850
      case ExecExhausted:
2851
      case PivotsExhauasted:
2852
        if(mipRes == BranchesExhausted){
2853
          ++d_statistics.d_branchesExhausted;
2854
        }else if(mipRes == ExecExhausted){
2855
          ++d_statistics.d_execExhausted;
2856
        }else if(mipRes == PivotsExhauasted){
2857
          ++d_statistics.d_pivotsExhausted;
2858
        }
2859
2860
        approx->setPivotLimit(2*mipLimit);
2861
        approx->setBranchingDepth(2);
2862
        {
2863
          TimerStat::CodeTimer codeTimer3(d_statistics.d_mipTimer);
2864
          mipRes = approx->solveMIP(true);
2865
        }
2866
        replayLemmas(approx);
2867
        break;
2868
      case MipUnknown:
2869
        break;
2870
      }
2871
    }
2872
  delete approx;
2873
2874
  if(!Theory::fullEffort(effortLevel)){
2875
    if(anyConflict() || !d_approxCuts.empty()){
2876
      d_solveIntMaybeHelp++;
2877
    }
2878
  }
2879
2880
  d_statistics.d_inSolveInteger = 0;
2881
}
2882
2883
1707941
SimplexDecisionProcedure& TheoryArithPrivate::selectSimplex(bool pass1){
2884
1707941
  if(pass1){
2885
1707941
    if(d_pass1SDP == NULL){
2886
6368
      if (options().arith.useFC)
2887
      {
2888
        d_pass1SDP = (SimplexDecisionProcedure*)(&d_fcSimplex);
2889
      }
2890
6368
      else if (options().arith.useSOI)
2891
      {
2892
        d_pass1SDP = (SimplexDecisionProcedure*)(&d_soiSimplex);
2893
      }
2894
      else
2895
      {
2896
6368
        d_pass1SDP = (SimplexDecisionProcedure*)(&d_dualSimplex);
2897
      }
2898
    }
2899
1707941
    Assert(d_pass1SDP != NULL);
2900
1707941
    return *d_pass1SDP;
2901
  }else{
2902
     if(d_otherSDP == NULL){
2903
       if (options().arith.useFC)
2904
       {
2905
         d_otherSDP = (SimplexDecisionProcedure*)(&d_fcSimplex);
2906
       }
2907
       else if (options().arith.useSOI)
2908
       {
2909
         d_otherSDP = (SimplexDecisionProcedure*)(&d_soiSimplex);
2910
       }
2911
       else
2912
       {
2913
         d_otherSDP = (SimplexDecisionProcedure*)(&d_soiSimplex);
2914
       }
2915
    }
2916
    Assert(d_otherSDP != NULL);
2917
    return *d_otherSDP;
2918
  }
2919
}
2920
2921
void TheoryArithPrivate::importSolution(const ApproximateSimplex::Solution& solution){
2922
  if(Debug.isOn("arith::importSolution")){
2923
    Debug("arith::importSolution") << "importSolution before " << d_qflraStatus << endl;
2924
    d_partialModel.printEntireModel(Debug("arith::importSolution"));
2925
  }
2926
2927
  d_qflraStatus = d_attemptSolSimplex.attempt(solution);
2928
2929
  if(Debug.isOn("arith::importSolution")){
2930
    Debug("arith::importSolution") << "importSolution intermediate " << d_qflraStatus << endl;
2931
    d_partialModel.printEntireModel(Debug("arith::importSolution"));
2932
  }
2933
2934
  if(d_qflraStatus != Result::UNSAT){
2935
    static const int64_t pass2Limit = 20;
2936
    int64_t oldCap = options().arith.arithStandardCheckVarOrderPivots;
2937
    Options::current().arith.arithStandardCheckVarOrderPivots = pass2Limit;
2938
    SimplexDecisionProcedure& simplex = selectSimplex(false);
2939
    d_qflraStatus = simplex.findModel(false);
2940
    Options::current().arith.arithStandardCheckVarOrderPivots = oldCap;
2941
  }
2942
2943
  if(Debug.isOn("arith::importSolution")){
2944
    Debug("arith::importSolution") << "importSolution after " << d_qflraStatus << endl;
2945
    d_partialModel.printEntireModel(Debug("arith::importSolution"));
2946
  }
2947
}
2948
2949
1707941
bool TheoryArithPrivate::solveRelaxationOrPanic(Theory::Effort effortLevel)
2950
{
2951
  // if at this point the linear relaxation is still unknown,
2952
  //  attempt to branch an integer variable as a last ditch effort on full check
2953
1707941
  if (d_qflraStatus == Result::SAT_UNKNOWN)
2954
  {
2955
    d_qflraStatus = selectSimplex(true).findModel(false);
2956
  }
2957
2958
1707941
  if (Theory::fullEffort(effortLevel) && d_qflraStatus == Result::SAT_UNKNOWN)
2959
  {
2960
    ArithVar canBranch = nextIntegerViolation(false);
2961
    if (canBranch != ARITHVAR_SENTINEL)
2962
    {
2963
      ++d_statistics.d_panicBranches;
2964
      TrustNode branch = branchIntegerVariable(canBranch);
2965
      Assert(branch.getNode().getKind() == kind::OR);
2966
      Node rwbranch = Rewriter::rewrite(branch.getNode()[0]);
2967
      if (!isSatLiteral(rwbranch))
2968
      {
2969
        d_approxCuts.push_back(branch);
2970
        return true;
2971
      }
2972
    }
2973
    d_qflraStatus = selectSimplex(false).findModel(true);
2974
  }
2975
1707941
  return false;
2976
}
2977
2978
1707941
bool TheoryArithPrivate::solveRealRelaxation(Theory::Effort effortLevel){
2979
3415882
  TimerStat::CodeTimer codeTimer0(d_statistics.d_solveRealRelaxTimer);
2980
1707941
  Assert(d_qflraStatus != Result::SAT);
2981
2982
1707941
  d_partialModel.stopQueueingBoundCounts();
2983
3415882
  UpdateTrackingCallback utcb(&d_linEq);
2984
1707941
  d_partialModel.processBoundsQueue(utcb);
2985
1707941
  d_linEq.startTrackingBoundCounts();
2986
2987
  bool noPivotLimit =
2988
1707941
      Theory::fullEffort(effortLevel) || !options().arith.restrictedPivots;
2989
2990
1707941
  SimplexDecisionProcedure& simplex = selectSimplex(true);
2991
2992
1707941
  bool useApprox = options().arith.useApprox && ApproximateSimplex::enabled()
2993
1707941
                   && getSolveIntegerResource();
2994
2995
3415882
  Debug("TheoryArithPrivate::solveRealRelaxation")
2996
1707941
      << "solveRealRelaxation() approx"
2997
1707941
      << " " << options().arith.useApprox << " "
2998
3415882
      << ApproximateSimplex::enabled() << " " << useApprox << " "
2999
1707941
      << safeToCallApprox() << endl;
3000
3001
1707941
  bool noPivotLimitPass1 = noPivotLimit && !useApprox;
3002
1707941
  d_qflraStatus = simplex.findModel(noPivotLimitPass1);
3003
3004
3415882
  Debug("TheoryArithPrivate::solveRealRelaxation")
3005
1707941
    << "solveRealRelaxation()" << " pass1 " << d_qflraStatus << endl;
3006
3007
1707941
  if(d_qflraStatus == Result::SAT_UNKNOWN && useApprox && safeToCallApprox()){
3008
    // pass2: fancy-final
3009
    static const int32_t relaxationLimit = 10000;
3010
    Assert(ApproximateSimplex::enabled());
3011
3012
    TreeLog& tl = getTreeLog();
3013
    ApproximateStatistics& stats = getApproxStats();
3014
    ApproximateSimplex* approxSolver =
3015
      ApproximateSimplex::mkApproximateSimplexSolver(d_partialModel, tl, stats);
3016
3017
    approxSolver->setPivotLimit(relaxationLimit);
3018
3019
    if(!d_guessedCoeffSet){
3020
      d_guessedCoeffs = approxSolver->heuristicOptCoeffs();
3021
      d_guessedCoeffSet = true;
3022
    }
3023
    if(!d_guessedCoeffs.empty()){
3024
      approxSolver->setOptCoeffs(d_guessedCoeffs);
3025
    }
3026
3027
    ++d_statistics.d_relaxCalls;
3028
3029
    ApproximateSimplex::Solution relaxSolution;
3030
    LinResult relaxRes = LinUnknown;
3031
    {
3032
      TimerStat::CodeTimer codeTimer1(d_statistics.d_lpTimer);
3033
      relaxRes = approxSolver->solveRelaxation();
3034
    }
3035
      Debug("solveRealRelaxation") << "solve relaxation? " << endl;
3036
      switch(relaxRes){
3037
      case LinFeasible:
3038
        Debug("solveRealRelaxation") << "lin feasible? " << endl;
3039
        ++d_statistics.d_relaxLinFeas;
3040
        relaxSolution = approxSolver->extractRelaxation();
3041
        importSolution(relaxSolution);
3042
        if(d_qflraStatus != Result::SAT){
3043
          ++d_statistics.d_relaxLinFeasFailures;
3044
        }
3045
        break;
3046
      case LinInfeasible:
3047
        // todo attempt to recreate approximate conflict
3048
        ++d_statistics.d_relaxLinInfeas;
3049
        Debug("solveRealRelaxation") << "lin infeasible " << endl;
3050
        relaxSolution = approxSolver->extractRelaxation();
3051
        importSolution(relaxSolution);
3052
        if(d_qflraStatus != Result::UNSAT){
3053
          ++d_statistics.d_relaxLinInfeasFailures;
3054
        }
3055
        break;
3056
      case LinExhausted:
3057
        ++d_statistics.d_relaxLinExhausted;
3058
        Debug("solveRealRelaxation") << "exhuasted " << endl;
3059
        break;
3060
      case LinUnknown:
3061
      default:
3062
        ++d_statistics.d_relaxOthers;
3063
        break;
3064
      }
3065
    delete approxSolver;
3066
3067
  }
3068
3069
1707941
  bool emmittedConflictOrSplit = solveRelaxationOrPanic(effortLevel);
3070
3071
  // TODO Save zeroes with no conflicts
3072
1707941
  d_linEq.stopTrackingBoundCounts();
3073
1707941
  d_partialModel.startQueueingBoundCounts();
3074
3075
3415882
  return emmittedConflictOrSplit;
3076
}
3077
3078
bool TheoryArithPrivate::hasFreshArithLiteral(Node n) const{
3079
  switch(n.getKind()){
3080
  case kind::LEQ:
3081
  case kind::GEQ:
3082
  case kind::GT:
3083
  case kind::LT:
3084
    return !isSatLiteral(n);
3085
  case kind::EQUAL:
3086
    if(n[0].getType().isReal()){
3087
      return !isSatLiteral(n);
3088
    }else if(n[0].getType().isBoolean()){
3089
      return hasFreshArithLiteral(n[0]) ||
3090
        hasFreshArithLiteral(n[1]);
3091
    }else{
3092
      return false;
3093
    }
3094
  case kind::IMPLIES:
3095
    // try the rhs first
3096
    return hasFreshArithLiteral(n[1]) ||
3097
      hasFreshArithLiteral(n[0]);
3098
  default:
3099
    if(n.getType().isBoolean()){
3100
      for(Node::iterator ni=n.begin(), nend=n.end(); ni!=nend; ++ni){
3101
        Node child = *ni;
3102
        if(hasFreshArithLiteral(child)){
3103
          return true;
3104
        }
3105
      }
3106
    }
3107
    return false;
3108
  }
3109
}
3110
3111
1786370
bool TheoryArithPrivate::preCheck(Theory::Effort level)
3112
{
3113
1786370
  Assert(d_currentPropagationList.empty());
3114
1786370
  if(Debug.isOn("arith::consistency")){
3115
    Assert(unenqueuedVariablesAreConsistent());
3116
  }
3117
3118
1786370
  d_newFacts = !done();
3119
  // If d_previousStatus == SAT, then reverts on conflicts are safe
3120
  // Otherwise, they are not and must be committed.
3121
1786370
  d_previousStatus = d_qflraStatus;
3122
1786370
  if (d_newFacts)
3123
  {
3124
1718890
    d_qflraStatus = Result::SAT_UNKNOWN;
3125
1718890
    d_hasDoneWorkSinceCut = true;
3126
  }
3127
1786370
  return false;
3128
}
3129
3130
5896760
void TheoryArithPrivate::preNotifyFact(TNode atom, bool pol, TNode fact)
3131
{
3132
5896760
  ConstraintP curr = constraintFromFactQueue(fact);
3133
5896760
  if (curr != NullConstraint)
3134
  {
3135
5591805
    bool res CVC5_UNUSED = assertionCases(curr);
3136
5591805
    Assert(!res || anyConflict());
3137
  }
3138
5896760
}
3139
3140
1783107
bool TheoryArithPrivate::postCheck(Theory::Effort effortLevel)
3141
{
3142
1783107
  if(!anyConflict()){
3143
2037937
    while(!d_learnedBounds.empty()){
3144
      // we may attempt some constraints twice.  this is okay!
3145
134411
      ConstraintP curr = d_learnedBounds.front();
3146
134411
      d_learnedBounds.pop();
3147
134411
      Debug("arith::learned") << curr << endl;
3148
3149
134411
      bool res CVC5_UNUSED = assertionCases(curr);
3150
134411
      Assert(!res || anyConflict());
3151
3152
134411
      if(anyConflict()){ break; }
3153
    }
3154
  }
3155
3156
1783107
  if(anyConflict()){
3157
13925
    d_qflraStatus = Result::UNSAT;
3158
13925
    if (options().arith.revertArithModels && d_previousStatus == Result::SAT)
3159
    {
3160
      ++d_statistics.d_revertsOnConflicts;
3161
      Debug("arith::bt") << "clearing here "
3162
                         << " " << d_newFacts << " " << d_previousStatus << " "
3163
                         << d_qflraStatus << endl;
3164
      revertOutOfConflict();
3165
      d_errorSet.clear();
3166
    }else{
3167
13925
      ++d_statistics.d_commitsOnConflicts;
3168
27850
      Debug("arith::bt") << "committing here "
3169
13925
                         << " " << d_newFacts << " " << d_previousStatus << " "
3170
13925
                         << d_qflraStatus << endl;
3171
13925
      d_partialModel.commitAssignmentChanges();
3172
13925
      revertOutOfConflict();
3173
    }
3174
13925
    outputConflicts();
3175
    //cout << "unate conflict 1 " << effortLevel << std::endl;
3176
13925
    return true;
3177
  }
3178
3179
3180
1769182
  if(Debug.isOn("arith::print_assertions")) {
3181
    debugPrintAssertions(Debug("arith::print_assertions"));
3182
  }
3183
3184
1769182
  bool emmittedConflictOrSplit = false;
3185
1769182
  Assert(d_conflicts.empty());
3186
3187
1769182
  bool useSimplex = d_qflraStatus != Result::SAT;
3188
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3189
1769182
                      << "pre realRelax" << endl;
3190
3191
1769182
  if(useSimplex){
3192
1707941
    emmittedConflictOrSplit = solveRealRelaxation(effortLevel);
3193
  }
3194
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3195
1769182
                      << "post realRelax" << endl;
3196
3197
3198
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3199
1769182
                      << "pre solveInteger" << endl;
3200
3201
1769182
  if(attemptSolveInteger(effortLevel, emmittedConflictOrSplit)){
3202
    solveInteger(effortLevel);
3203
    if(anyConflict()){
3204
      ++d_statistics.d_commitsOnConflicts;
3205
      Debug("arith::bt") << "committing here "
3206
                         << " " << d_newFacts << " " << d_previousStatus << " "
3207
                         << d_qflraStatus << endl;
3208
      revertOutOfConflict();
3209
      d_errorSet.clear();
3210
      outputConflicts();
3211
      return true;
3212
    }
3213
  }
3214
3215
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3216
1769182
                      << "post solveInteger" << endl;
3217
3218
1769182
  switch(d_qflraStatus){
3219
1726195
  case Result::SAT:
3220
1726195
    if (d_newFacts)
3221
    {
3222
1661978
      ++d_statistics.d_nontrivialSatChecks;
3223
    }
3224
3225
3452390
    Debug("arith::bt") << "committing sap inConflit"
3226
1726195
                       << " " << d_newFacts << " " << d_previousStatus << " "
3227
1726195
                       << d_qflraStatus << endl;
3228
1726195
    d_partialModel.commitAssignmentChanges();
3229
1726195
    d_unknownsInARow = 0;
3230
1726195
    if(Debug.isOn("arith::consistency")){
3231
      Assert(entireStateIsConsistent("sat comit"));
3232
    }
3233
1726195
    if (useSimplex && options().arith.collectPivots)
3234
    {
3235
      if (options().arith.useFC)
3236
      {
3237
        d_statistics.d_satPivots << d_fcSimplex.getPivots();
3238
      }
3239
      else
3240
      {
3241
        d_statistics.d_satPivots << d_dualSimplex.getPivots();
3242
      }
3243
    }
3244
1726195
    break;
3245
  case Result::SAT_UNKNOWN:
3246
    ++d_unknownsInARow;
3247
    ++(d_statistics.d_unknownChecks);
3248
    Assert(!Theory::fullEffort(effortLevel));
3249
    Debug("arith::bt") << "committing unknown"
3250
                       << " " << d_newFacts << " " << d_previousStatus << " "
3251
                       << d_qflraStatus << endl;
3252
    d_partialModel.commitAssignmentChanges();
3253
    d_statistics.d_maxUnknownsInARow.maxAssign(d_unknownsInARow);
3254
3255
    if (useSimplex && options().arith.collectPivots)
3256
    {
3257
      if (options().arith.useFC)
3258
      {
3259
        d_statistics.d_unknownPivots << d_fcSimplex.getPivots();
3260
      }
3261
      else
3262
      {
3263
        d_statistics.d_unknownPivots << d_dualSimplex.getPivots();
3264
      }
3265
    }
3266
    break;
3267
42987
  case Result::UNSAT:
3268
42987
    d_unknownsInARow = 0;
3269
3270
42987
    ++d_statistics.d_commitsOnConflicts;
3271
3272
85974
    Debug("arith::bt") << "committing on conflict"
3273
42987
                       << " " << d_newFacts << " " << d_previousStatus << " "
3274
42987
                       << d_qflraStatus << endl;
3275
42987
    d_partialModel.commitAssignmentChanges();
3276
42987
    revertOutOfConflict();
3277
3278
42987
    if(Debug.isOn("arith::consistency::comitonconflict")){
3279
      entireStateIsConsistent("commit on conflict");
3280
    }
3281
42987
    outputConflicts();
3282
42987
    emmittedConflictOrSplit = true;
3283
42987
    Debug("arith::conflict") << "simplex conflict" << endl;
3284
3285
42987
    if (useSimplex && options().arith.collectPivots)
3286
    {
3287
      if (options().arith.useFC)
3288
      {
3289
        d_statistics.d_unsatPivots << d_fcSimplex.getPivots();
3290
      }
3291
      else
3292
      {
3293
        d_statistics.d_unsatPivots << d_dualSimplex.getPivots();
3294
      }
3295
    }
3296
42987
    break;
3297
  default:
3298
    Unimplemented();
3299
  }
3300
1769182
  d_statistics.d_avgUnknownsInARow << d_unknownsInARow;
3301
3302
3538364
  size_t nPivots = options().arith.useFC ? d_fcSimplex.getPivots()
3303
3538364
                                         : d_dualSimplex.getPivots();
3304
1981657
  for (std::size_t i = 0; i < nPivots; ++i)
3305
  {
3306
424950
    d_containing.d_out->spendResource(
3307
212475
        Resource::ArithPivotStep);
3308
  }
3309
3310
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3311
1769182
                      << "pre approx cuts" << endl;
3312
1769182
  if(!d_approxCuts.empty()){
3313
    bool anyFresh = false;
3314
    while(!d_approxCuts.empty()){
3315
      TrustNode lem = d_approxCuts.front();
3316
      d_approxCuts.pop();
3317
      Debug("arith::approx::cuts") << "approximate cut:" << lem << endl;
3318
      anyFresh = anyFresh || hasFreshArithLiteral(lem.getNode());
3319
      Debug("arith::lemma") << "approximate cut:" << lem << endl;
3320
      outputTrustedLemma(lem, InferenceId::ARITH_APPROX_CUT);
3321
    }
3322
    if(anyFresh){
3323
      emmittedConflictOrSplit = true;
3324
    }
3325
  }
3326
3327
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3328
1769182
                      << "post approx cuts" << endl;
3329
3330
  // This should be fine if sat or unknown
3331
3538364
  if (!emmittedConflictOrSplit
3332
3495377
      && (options().arith.arithPropagationMode
3333
              == options::ArithPropagationMode::UNATE_PROP
3334
1726195
          || options().arith.arithPropagationMode
3335
                 == options::ArithPropagationMode::BOTH_PROP))
3336
  {
3337
3452390
    TimerStat::CodeTimer codeTimer0(d_statistics.d_newPropTime);
3338
1726195
    Assert(d_qflraStatus != Result::UNSAT);
3339
3340
7630283
    while(!d_currentPropagationList.empty()  && !anyConflict()){
3341
2952044
      ConstraintP curr = d_currentPropagationList.front();
3342
2952044
      d_currentPropagationList.pop_front();
3343
3344
2952044
      ConstraintType t = curr->getType();
3345
2952044
      Assert(t != Disequality)
3346
          << "Disequalities are not allowed in d_currentPropagation";
3347
3348
2952044
      switch(t){
3349
1043666
      case LowerBound:
3350
        {
3351
1043666
          ConstraintP prev = d_currentPropagationList.front();
3352
1043666
          d_currentPropagationList.pop_front();
3353
1043666
          d_constraintDatabase.unatePropLowerBound(curr, prev);
3354
1043666
          break;
3355
        }
3356
931317
      case UpperBound:
3357
        {
3358
931317
          ConstraintP prev = d_currentPropagationList.front();
3359
931317
          d_currentPropagationList.pop_front();
3360
931317
          d_constraintDatabase.unatePropUpperBound(curr, prev);
3361
931317
          break;
3362
        }
3363
977061
      case Equality:
3364
        {
3365
977061
          ConstraintP prevLB = d_currentPropagationList.front();
3366
977061
          d_currentPropagationList.pop_front();
3367
977061
          ConstraintP prevUB = d_currentPropagationList.front();
3368
977061
          d_currentPropagationList.pop_front();
3369
977061
          d_constraintDatabase.unatePropEquality(curr, prevLB, prevUB);
3370
977061
          break;
3371
        }
3372
        default: Unhandled() << curr->getType();
3373
      }
3374
    }
3375
3376
1726195
    if(anyConflict()){
3377
      Debug("arith::unate") << "unate conflict" << endl;
3378
      revertOutOfConflict();
3379
      d_qflraStatus = Result::UNSAT;
3380
      outputConflicts();
3381
      emmittedConflictOrSplit = true;
3382
      //cout << "unate conflict " << endl;
3383
      Debug("arith::bt") << "committing on unate conflict"
3384
                         << " " << d_newFacts << " " << d_previousStatus << " "
3385
                         << d_qflraStatus << endl;
3386
3387
      Debug("arith::conflict") << "unate arith conflict" << endl;
3388
    }
3389
  }
3390
  else
3391
  {
3392
85974
    TimerStat::CodeTimer codeTimer1(d_statistics.d_newPropTime);
3393
42987
    d_currentPropagationList.clear();
3394
  }
3395
1769182
  Assert(d_currentPropagationList.empty());
3396
3397
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3398
1769182
                      << "post unate" << endl;
3399
3400
1769182
  if(!emmittedConflictOrSplit && Theory::fullEffort(effortLevel)){
3401
67514
    ++d_fullCheckCounter;
3402
  }
3403
1769182
  if(!emmittedConflictOrSplit && Theory::fullEffort(effortLevel)){
3404
67514
    emmittedConflictOrSplit = splitDisequalities();
3405
  }
3406
3538364
  Debug("arith::ems") << "ems: " << emmittedConflictOrSplit
3407
1769182
                      << "pos splitting" << endl;
3408
3409
3410
3538364
  Debug("arith") << "integer? "
3411
1769182
       << " conf/split " << emmittedConflictOrSplit
3412
3538364
       << " fulleffort " << Theory::fullEffort(effortLevel)
3413
1769182
       << " hasintmodel " << hasIntegerModel() << endl;
3414
3415
1769182
  if(!emmittedConflictOrSplit && Theory::fullEffort(effortLevel) && !hasIntegerModel()){
3416
5532
    Node possibleConflict = Node::null();
3417
2766
    if (!emmittedConflictOrSplit && options().arith.arithDioSolver)
3418
    {
3419
2766
      possibleConflict = callDioSolver();
3420
2766
      if(possibleConflict != Node::null()){
3421
174
        revertOutOfConflict();
3422
174
        Debug("arith::conflict") << "dio conflict   " << possibleConflict << endl;
3423
        // TODO (project #37): justify (proofs in the DIO solver)
3424
174
        raiseBlackBoxConflict(possibleConflict);
3425
174
        outputConflicts();
3426
174
        emmittedConflictOrSplit = true;
3427
      }
3428
    }
3429
3430
8124
    if (!emmittedConflictOrSplit && d_hasDoneWorkSinceCut
3431
5358
        && options().arith.arithDioSolver)
3432
    {
3433
2592
      if(getDioCuttingResource()){
3434
3838
        TrustNode possibleLemma = dioCutting();
3435
1919
        if(!possibleLemma.isNull()){
3436
1459
          d_hasDoneWorkSinceCut = false;
3437
1459
          d_cutCount = d_cutCount + 1;
3438
1459
          Debug("arith::lemma") << "dio cut   " << possibleLemma << endl;
3439
1459
          if (outputTrustedLemma(possibleLemma, InferenceId::ARITH_DIO_CUT))
3440
          {
3441
1459
            emmittedConflictOrSplit = true;
3442
          }
3443
        }
3444
      }
3445
    }
3446
3447
2766
    if(!emmittedConflictOrSplit) {
3448
2266
      TrustNode possibleLemma = roundRobinBranch();
3449
1133
      if (!possibleLemma.getNode().isNull())
3450
      {
3451
1133
        ++(d_statistics.d_externalBranchAndBounds);
3452
1133
        d_cutCount = d_cutCount + 1;
3453
2266
        Debug("arith::lemma") << "rrbranch lemma"
3454
1133
                              << possibleLemma << endl;
3455
1133
        if (outputTrustedLemma(possibleLemma, InferenceId::ARITH_BB_LEMMA))
3456
        {
3457
1133
          emmittedConflictOrSplit = true;
3458
        }
3459
      }
3460
    }
3461
3462
2766
    if (options().arith.maxCutsInContext <= d_cutCount)
3463
    {
3464
      if(d_diosolver.hasMoreDecompositionLemmas()){
3465
        while(d_diosolver.hasMoreDecompositionLemmas()){
3466
          Node decompositionLemma = d_diosolver.nextDecompositionLemma();
3467
          Debug("arith::lemma") << "dio decomposition lemma "
3468
                                << decompositionLemma << endl;
3469
          outputLemma(decompositionLemma, InferenceId::ARITH_DIO_DECOMPOSITION);
3470
        }
3471
      }else{
3472
        Debug("arith::restart") << "arith restart!" << endl;
3473
        outputRestart();
3474
      }
3475
    }
3476
  }//if !emmittedConflictOrSplit && fullEffort(effortLevel) && !hasIntegerModel()
3477
3478
1769182
  if(Theory::fullEffort(effortLevel)){
3479
74677
    if(Debug.isOn("arith::consistency::final")){
3480
      entireStateIsConsistent("arith::consistency::final");
3481
    }
3482
  }
3483
3484
1769182
  if(Debug.isOn("paranoid:check_tableau")){ d_linEq.debugCheckTableau(); }
3485
1769182
  if(Debug.isOn("arith::print_model")) {
3486
    debugPrintModel(Debug("arith::print_model"));
3487
  }
3488
1769182
  Debug("arith") << "TheoryArithPrivate::check end" << std::endl;
3489
1769182
  return emmittedConflictOrSplit;
3490
}
3491
3492
29844
bool TheoryArithPrivate::foundNonlinear() const { return d_foundNl; }
3493
3494
1133
TrustNode TheoryArithPrivate::branchIntegerVariable(ArithVar x) const
3495
{
3496
1133
  const DeltaRational& d = d_partialModel.getAssignment(x);
3497
1133
  Assert(!d.isIntegral());
3498
1133
  const Rational& r = d.getNoninfinitesimalPart();
3499
1133
  const Rational& i = d.getInfinitesimalPart();
3500
1133
  Trace("integers") << "integers: assignment to [[" << d_partialModel.asNode(x) << "]] is " << r << "[" << i << "]" << endl;
3501
1133
  Assert(!(r.getDenominator() == 1 && i.getNumerator() == 0));
3502
2266
  TNode var = d_partialModel.asNode(x);
3503
1133
  TrustNode lem = d_bab.branchIntegerVariable(var, r);
3504
1133
  if (Debug.isOn("integers"))
3505
  {
3506
    Node l = lem.getNode();
3507
    if (isSatLiteral(l[0]))
3508
    {
3509
      Debug("integers") << "    " << l[0] << " == " << getSatValue(l[0])
3510
                        << endl;
3511
    }
3512
    else
3513
    {
3514
      Debug("integers") << "    " << l[0] << " is not assigned a SAT literal"
3515
                        << endl;
3516
    }
3517
    if (isSatLiteral(l[1]))
3518
    {
3519
      Debug("integers") << "    " << l[1] << " == " << getSatValue(l[1])
3520
                        << endl;
3521
    }
3522
    else
3523
    {
3524
      Debug("integers") << "    " << l[1] << " is not assigned a SAT literal"
3525
                        << endl;
3526
    }
3527
  }
3528
2266
  return lem;
3529
}
3530
3531
std::vector<ArithVar> TheoryArithPrivate::cutAllBounded() const{
3532
  vector<ArithVar> lemmas;
3533
  ArithVar max = d_partialModel.getNumberOfVariables();
3534
3535
  if (options().arith.doCutAllBounded && max > 0)
3536
  {
3537
    for(ArithVar iter = 0; iter != max; ++iter){
3538
    //Do not include slack variables
3539
      const DeltaRational& d = d_partialModel.getAssignment(iter);
3540
      if(isIntegerInput(iter) &&
3541
         !d_cutInContext.contains(iter) &&
3542
         d_partialModel.hasUpperBound(iter) &&
3543
         d_partialModel.hasLowerBound(iter) &&
3544
         !d.isIntegral()){
3545
        lemmas.push_back(iter);
3546
      }
3547
    }
3548
  }
3549
  return lemmas;
3550
}
3551
3552
/** Returns true if the roundRobinBranching() issues a lemma. */
3553
1133
TrustNode TheoryArithPrivate::roundRobinBranch()
3554
{
3555
1133
  if(hasIntegerModel()){
3556
    return TrustNode::null();
3557
  }else{
3558
1133
    ArithVar v = d_nextIntegerCheckVar;
3559
3560
1133
    Assert(isInteger(v));
3561
1133
    Assert(!isAuxiliaryVariable(v));
3562
1133
    return branchIntegerVariable(v);
3563
  }
3564
}
3565
3566
67514
bool TheoryArithPrivate::splitDisequalities(){
3567
67514
  bool splitSomething = false;
3568
3569
135028
  vector<ConstraintP> save;
3570
3571
607710
  while(!d_diseqQueue.empty()){
3572
270098
    ConstraintP front = d_diseqQueue.front();
3573
270098
    d_diseqQueue.pop();
3574
3575
270098
    if(front->isSplit()){
3576
212
      Debug("arith::eq") << "split already" << endl;
3577
    }else{
3578
269886
      Debug("arith::eq") << "not split already" << endl;
3579
3580
269886
      ArithVar lhsVar = front->getVariable();
3581
3582
269886
      const DeltaRational& lhsValue = d_partialModel.getAssignment(lhsVar);
3583
269886
      const DeltaRational& rhsValue = front->getValue();
3584
269886
      if(lhsValue == rhsValue){
3585
208
        Debug("arith::lemma") << "Splitting on " << front << endl;
3586
208
        Debug("arith::lemma") << "LHS value = " << lhsValue << endl;
3587
208
        Debug("arith::lemma") << "RHS value = " << rhsValue << endl;
3588
416
        TrustNode lemma = front->split();
3589
208
        ++(d_statistics.d_statDisequalitySplits);
3590
3591
416
        Debug("arith::lemma")
3592
208
            << "Now " << Rewriter::rewrite(lemma.getNode()) << endl;
3593
208
        outputTrustedLemma(lemma, InferenceId::ARITH_SPLIT_DEQ);
3594
        //cout << "Now " << Rewriter::rewrite(lemma) << endl;
3595
208
        splitSomething = true;
3596
269678
      }else if(d_partialModel.strictlyLessThanLowerBound(lhsVar, rhsValue)){
3597
56505
        Debug("arith::eq") << "can drop as less than lb" << front << endl;
3598
213173
      }else if(d_partialModel.strictlyGreaterThanUpperBound(lhsVar, rhsValue)){
3599
22453
        Debug("arith::eq") << "can drop as greater than ub" << front << endl;
3600
      }else{
3601
190720
        Debug("arith::eq") << "save" << front << ": " <<lhsValue << " != " << rhsValue << endl;
3602
190720
        save.push_back(front);
3603
      }
3604
    }
3605
  }
3606
67514
  vector<ConstraintP>::const_iterator i=save.begin(), i_end = save.end();
3607
448954
  for(; i != i_end; ++i){
3608
190720
    d_diseqQueue.push(*i);
3609
  }
3610
135028
  return splitSomething;
3611
}
3612
3613
/**
3614
 * Should be guarded by at least Debug.isOn("arith::print_assertions").
3615
 * Prints to Debug("arith::print_assertions")
3616
 */
3617
void TheoryArithPrivate::debugPrintAssertions(std::ostream& out) const {
3618
  out << "Assertions:" << endl;
3619
  for (var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
3620
    ArithVar i = *vi;
3621
    if (d_partialModel.hasLowerBound(i)) {
3622
      ConstraintP lConstr = d_partialModel.getLowerBoundConstraint(i);
3623
      out << lConstr << endl;
3624
    }
3625
3626
    if (d_partialModel.hasUpperBound(i)) {
3627
      ConstraintP uConstr = d_partialModel.getUpperBoundConstraint(i);
3628
      out << uConstr << endl;
3629
    }
3630
  }
3631
  context::CDQueue<ConstraintP>::const_iterator it = d_diseqQueue.begin();
3632
  context::CDQueue<ConstraintP>::const_iterator it_end = d_diseqQueue.end();
3633
  for(; it != it_end; ++ it) {
3634
    out << *it << endl;
3635
  }
3636
}
3637
3638
void TheoryArithPrivate::debugPrintModel(std::ostream& out) const{
3639
  out << "Model:" << endl;
3640
  for (var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
3641
    ArithVar i = *vi;
3642
    if(d_partialModel.hasNode(i)){
3643
      out << d_partialModel.asNode(i) << " : " <<
3644
        d_partialModel.getAssignment(i);
3645
      if(d_tableau.isBasic(i)){
3646
        out << " (basic)";
3647
      }
3648
      out << endl;
3649
    }
3650
  }
3651
}
3652
3653
30413
TrustNode TheoryArithPrivate::explain(TNode n)
3654
{
3655
30413
  Debug("arith::explain") << "explain @" << getSatContext()->getLevel() << ": " << n << endl;
3656
3657
30413
  ConstraintP c = d_constraintDatabase.lookup(n);
3658
30413
  TrustNode exp;
3659
30413
  if(c != NullConstraint){
3660
11600
    Assert(!c->isAssumption());
3661
11600
    exp = c->externalExplainForPropagation(n);
3662
11600
    Debug("arith::explain") << "constraint explanation" << n << ":" << exp << endl;
3663
18813
  }else if(d_assertionsThatDoNotMatchTheirLiterals.find(n) != d_assertionsThatDoNotMatchTheirLiterals.end()){
3664
15038
    c = d_assertionsThatDoNotMatchTheirLiterals[n];
3665
15038
    if(!c->isAssumption()){
3666
4769
      exp = c->externalExplainForPropagation(n);
3667
4769
      Debug("arith::explain") << "assertions explanation" << n << ":" << exp << endl;
3668
    }else{
3669
10269
      Debug("arith::explain") << "this is a strange mismatch" << n << endl;
3670
10269
      Assert(d_congruenceManager.canExplain(n));
3671
10269
      exp = d_congruenceManager.explain(n);
3672
    }
3673
  }else{
3674
3775
    Assert(d_congruenceManager.canExplain(n));
3675
3775
    Debug("arith::explain") << "dm explanation" << n << endl;
3676
3775
    exp = d_congruenceManager.explain(n);
3677
  }
3678
30413
  return exp;
3679
}
3680
3681
2779544
void TheoryArithPrivate::propagate(Theory::Effort e) {
3682
  // This uses model values for safety. Disable for now.
3683
5559088
  if (d_qflraStatus == Result::SAT
3684
2752760
      && (options().arith.arithPropagationMode
3685
              == options::ArithPropagationMode::BOUND_INFERENCE_PROP
3686
2752760
          || options().arith.arithPropagationMode
3687
                 == options::ArithPropagationMode::BOTH_PROP)
3688
5532304
      && hasAnyUpdates())
3689
  {
3690
1093574
    if (options().arith.newProp)
3691
    {
3692
1091022
      propagateCandidatesNew();
3693
    }
3694
    else
3695
    {
3696
2552
      propagateCandidates();
3697
    }
3698
  }
3699
  else
3700
  {
3701
1685970
    clearUpdates();
3702
  }
3703
3704
4368494
  while(d_constraintDatabase.hasMorePropagations()){
3705
794475
    ConstraintCP c = d_constraintDatabase.nextPropagation();
3706
794475
    Debug("arith::prop") << "next prop" << getSatContext()->getLevel() << ": " << c << endl;
3707
3708
794475
    if(c->negationHasProof()){
3709
      Debug("arith::prop") << "negation has proof " << c->getNegation() << endl;
3710
      Debug("arith::prop") << c->getNegation()->externalExplainByAssertions()
3711
                           << endl;
3712
    }
3713
794475
    Assert(!c->negationHasProof())
3714
        << "A constraint has been propagated on the constraint propagation "
3715
           "queue, but the negation has been set to true.  Contact Tim now!";
3716
3717
794475
    if(!c->assertedToTheTheory()){
3718
1545442
      Node literal = c->getLiteral();
3719
772721
      Debug("arith::prop") << "propagating @" << getSatContext()->getLevel() << " " << literal << endl;
3720
3721
772721
      outputPropagate(literal);
3722
    }else{
3723
21754
      Debug("arith::prop") << "already asserted to the theory " <<  c->getLiteral() << endl;
3724
    }
3725
  }
3726
3727
4256430
  while(d_congruenceManager.hasMorePropagations()){
3728
1476886
    TNode toProp = d_congruenceManager.getNextPropagation();
3729
3730
    //Currently if the flag is set this came from an equality detected by the
3731
    //equality engine in the the difference manager.
3732
1476886
    Node normalized = Rewriter::rewrite(toProp);
3733
3734
738443
    ConstraintP constraint = d_constraintDatabase.lookup(normalized);
3735
738443
    if(constraint == NullConstraint){
3736
147
      Debug("arith::prop") << "propagating on non-constraint? "  << toProp << endl;
3737
3738
147
      outputPropagate(toProp);
3739
738296
    }else if(constraint->negationHasProof()){
3740
      // The congruence manager can prove: antecedents => toProp,
3741
      // ergo. antecedents ^ ~toProp is a conflict.
3742
      TrustNode exp = d_congruenceManager.explain(toProp);
3743
      Node notNormalized = normalized.negate();
3744
      std::vector<Node> ants(exp.getNode().begin(), exp.getNode().end());
3745
      ants.push_back(notNormalized);
3746
      Node lp = safeConstructNary(kind::AND, ants);
3747
      Debug("arith::prop") << "propagate conflict" <<  lp << endl;
3748
      if (proofsEnabled())
3749
      {
3750
        // Assume all of antecedents and ~toProp (rewritten)
3751
        std::vector<Pf> pfAntList;
3752
        for (size_t i = 0; i < ants.size(); ++i)
3753
        {
3754
          pfAntList.push_back(d_pnm->mkAssume(ants[i]));
3755
        }
3756
        Pf pfAnt = pfAntList.size() > 1
3757
                       ? d_pnm->mkNode(PfRule::AND_INTRO, pfAntList, {})
3758
                       : pfAntList[0];
3759
        // Use modus ponens to get toProp (un rewritten)
3760
        Pf pfConc = d_pnm->mkNode(
3761
            PfRule::MODUS_PONENS,
3762
            {pfAnt, exp.getGenerator()->getProofFor(exp.getProven())},
3763
            {});
3764
        // prove toProp (rewritten)
3765
        Pf pfConcRewritten = d_pnm->mkNode(
3766
            PfRule::MACRO_SR_PRED_TRANSFORM, {pfConc}, {normalized});
3767
        Pf pfNotNormalized = d_pnm->mkAssume(notNormalized);
3768
        // prove bottom from toProp and ~toProp
3769
        Pf pfBot;
3770
        if (normalized.getKind() == kind::NOT)
3771
        {
3772
          pfBot = d_pnm->mkNode(
3773
              PfRule::CONTRA, {pfNotNormalized, pfConcRewritten}, {});
3774
        }
3775
        else
3776
        {
3777
          pfBot = d_pnm->mkNode(
3778
              PfRule::CONTRA, {pfConcRewritten, pfNotNormalized}, {});
3779
        }
3780
        // close scope
3781
        Pf pfNotAnd = d_pnm->mkScope(pfBot, ants);
3782
        raiseBlackBoxConflict(lp, pfNotAnd);
3783
      }
3784
      else
3785
      {
3786
        raiseBlackBoxConflict(lp);
3787
      }
3788
      outputConflicts();
3789
      return;
3790
    }else{
3791
738296
      Debug("arith::prop") << "propagating still?" <<  toProp << endl;
3792
738296
      outputPropagate(toProp);
3793
    }
3794
  }
3795
}
3796
3797
6683657
DeltaRational TheoryArithPrivate::getDeltaValue(TNode term) const
3798
{
3799
6683657
  AlwaysAssert(d_qflraStatus != Result::SAT_UNKNOWN);
3800
6683657
  Debug("arith::value") << term << std::endl;
3801
3802
6683657
  if (d_partialModel.hasArithVar(term)) {
3803
2390946
    ArithVar var = d_partialModel.asArithVar(term);
3804
2390946
    return d_partialModel.getAssignment(var);
3805
  }
3806
3807
4292711
  switch (Kind kind = term.getKind()) {
3808
2452599
    case kind::CONST_RATIONAL:
3809
2452599
      return term.getConst<Rational>();
3810
3811
1339069
    case kind::PLUS: {  // 2+ args
3812
2678138
      DeltaRational value(0);
3813
4333863
      for (TNode::iterator i = term.begin(), iend = term.end(); i != iend;
3814
           ++i) {
3815
2994794
        value = value + getDeltaValue(*i);
3816
      }
3817
1339069
      return value;
3818
    }
3819
3820
501043
    case kind::NONLINEAR_MULT:
3821
    case kind::MULT: {  // 2+ args
3822
501043
      Assert(!isSetup(term));
3823
1002086
      DeltaRational value(1);
3824
1503129
      for (TNode::iterator i = term.begin(), iend = term.end(); i != iend;
3825
           ++i) {
3826
1002086
        value = value * getDeltaValue(*i);
3827
      }
3828
501043
      return value;
3829
    }
3830
    case kind::MINUS: {  // 2 args
3831
      return getDeltaValue(term[0]) - getDeltaValue(term[1]);
3832
    }
3833
    case kind::UMINUS: {  // 1 arg
3834
      return (-getDeltaValue(term[0]));
3835
    }
3836
3837
    case kind::DIVISION: {  // 2 args
3838
      Assert(!isSetup(term));
3839
      return getDeltaValue(term[0]) / getDeltaValue(term[1]);
3840
    }
3841
    case kind::DIVISION_TOTAL:
3842
    case kind::INTS_DIVISION_TOTAL:
3843
    case kind::INTS_MODULUS_TOTAL: {  // 2 args
3844
      Assert(!isSetup(term));
3845
      DeltaRational denominator = getDeltaValue(term[1]);
3846
      if (denominator.isZero()) {
3847
        return DeltaRational(0, 0);
3848
      }
3849
      DeltaRational numerator = getDeltaValue(term[0]);
3850
      if (kind == kind::DIVISION_TOTAL) {
3851
        return numerator / denominator;
3852
      } else if (kind == kind::INTS_DIVISION_TOTAL) {
3853
        return Rational(numerator.euclidianDivideQuotient(denominator));
3854
      } else {
3855
        Assert(kind == kind::INTS_MODULUS_TOTAL);
3856
        return Rational(numerator.euclidianDivideRemainder(denominator));
3857
      }
3858
    }
3859
3860
    default:
3861
      throw ModelException(term, "No model assignment.");
3862
  }
3863
}
3864
3865
28225
Rational TheoryArithPrivate::deltaValueForTotalOrder() const{
3866
56450
  Rational min(2);
3867
56450
  std::set<DeltaRational> relevantDeltaValues;
3868
28225
  context::CDQueue<ConstraintP>::const_iterator qiter = d_diseqQueue.begin();
3869
28225
  context::CDQueue<ConstraintP>::const_iterator qiter_end = d_diseqQueue.end();
3870
3871
187491
  for(; qiter != qiter_end; ++qiter){
3872
79633
    ConstraintP curr = *qiter;
3873
3874
79633
    const DeltaRational& rhsValue = curr->getValue();
3875
79633
    relevantDeltaValues.insert(rhsValue);
3876
  }
3877
3878
28225
  Theory::shared_terms_iterator shared_iter = d_containing.shared_terms_begin();
3879
28225
  Theory::shared_terms_iterator shared_end = d_containing.shared_terms_end();
3880
1751741
  for(; shared_iter != shared_end; ++shared_iter){
3881
1723516
    Node sharedCurr = *shared_iter;
3882
3883
    // ModelException is fatal as this point. Don't catch!
3884
    // DeltaRationalException is fatal as this point. Don't catch!
3885
1723516
    DeltaRational val = getDeltaValue(sharedCurr);
3886
861758
    relevantDeltaValues.insert(val);
3887
  }
3888
3889
2020304
  for(var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
3890
1992079
    ArithVar v = *vi;
3891
1992079
    const DeltaRational& value = d_partialModel.getAssignment(v);
3892
1992079
    relevantDeltaValues.insert(value);
3893
1992079
    if( d_partialModel.hasLowerBound(v)){
3894
1256558
      const DeltaRational& lb = d_partialModel.getLowerBound(v);
3895
1256558
      relevantDeltaValues.insert(lb);
3896
    }
3897
1992079
    if( d_partialModel.hasUpperBound(v)){
3898
1065709
      const DeltaRational& ub = d_partialModel.getUpperBound(v);
3899
1065709
      relevantDeltaValues.insert(ub);
3900
    }
3901
  }
3902
3903
28225
  if(relevantDeltaValues.size() >= 2){
3904
25383
    std::set<DeltaRational>::const_iterator iter = relevantDeltaValues.begin();
3905
25383
    std::set<DeltaRational>::const_iterator iter_end = relevantDeltaValues.end();
3906
50766
    DeltaRational prev = *iter;
3907
25383
    ++iter;
3908
605427
    for(; iter != iter_end; ++iter){
3909
290022
      const DeltaRational& curr = *iter;
3910
3911
290022
      Assert(prev < curr);
3912
3913
290022
      DeltaRational::seperatingDelta(min, prev, curr);
3914
290022
      prev = curr;
3915
    }
3916
  }
3917
3918
28225
  Assert(min.sgn() > 0);
3919
28225
  Rational belowMin = min/Rational(2);
3920
56450
  return belowMin;
3921
}
3922
3923
42935
void TheoryArithPrivate::collectModelValues(const std::set<Node>& termSet,
3924
                                            std::map<Node, Node>& arithModel)
3925
{
3926
42935
  AlwaysAssert(d_qflraStatus == Result::SAT);
3927
3928
42935
  if(Debug.isOn("arith::collectModelInfo")){
3929
    debugPrintFacts();
3930
  }
3931
3932
42935
  Debug("arith::collectModelInfo") << "collectModelInfo() begin " << endl;
3933
3934
  // Delta lasts at least the duration of the function call
3935
42935
  const Rational& delta = d_partialModel.getDelta();
3936
85870
  std::unordered_set<TNode> shared = d_containing.currentlySharedTerms();
3937
3938
  // TODO:
3939
  // This is not very good for user push/pop....
3940
  // Revisit when implementing push/pop
3941
2475704
  for(var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
3942
2432769
    ArithVar v = *vi;
3943
3944
2432769
    if(!isAuxiliaryVariable(v)){
3945
1995962
      Node term = d_partialModel.asNode(v);
3946
3947
3849861
      if((theoryOf(term) == THEORY_ARITH || shared.find(term) != shared.end())
3948
3962484
         && termSet.find(term) != termSet.end()){
3949
3950
960197
        const DeltaRational& mod = d_partialModel.getAssignment(v);
3951
1920394
        Rational qmodel = mod.substituteDelta(delta);
3952
3953
1920394
        Node qNode = mkRationalNode(qmodel);
3954
960197
        Debug("arith::collectModelInfo") << "m->assertEquality(" << term << ", " << qmodel << ", true)" << endl;
3955
        // Add to the map
3956
960197
        arithModel[term] = qNode;
3957
      }else{
3958
37784
        Debug("arith::collectModelInfo") << "Skipping m->assertEquality(" << term << ", true)" << endl;
3959
3960
      }
3961
    }
3962
  }
3963
3964
  // Iterate over equivalence classes in LinearEqualityModule
3965
  // const eq::EqualityEngine& ee = d_congruenceManager.getEqualityEngine();
3966
  // m->assertEqualityEngine(&ee);
3967
3968
42935
  Debug("arith::collectModelInfo") << "collectModelInfo() end " << endl;
3969
42935
}
3970
3971
bool TheoryArithPrivate::safeToReset() const {
3972
  Assert(!d_tableauSizeHasBeenModified);
3973
  Assert(d_errorSet.noSignals());
3974
3975
  ErrorSet::error_iterator error_iter = d_errorSet.errorBegin();
3976
  ErrorSet::error_iterator error_end = d_errorSet.errorEnd();
3977
  for(; error_iter != error_end; ++error_iter){
3978
    ArithVar basic = *error_iter;
3979
    if(!d_smallTableauCopy.isBasic(basic)){
3980
      return false;
3981
    }
3982
  }
3983
3984
  return true;
3985
}
3986
3987
1679
void TheoryArithPrivate::notifyRestart(){
3988
3358
  TimerStat::CodeTimer codeTimer(d_statistics.d_restartTimer);
3989
3990
1679
  if(Debug.isOn("paranoid:check_tableau")){ d_linEq.debugCheckTableau(); }
3991
3992
1679
  ++d_restartsCounter;
3993
1679
  d_solveIntMaybeHelp = 0;
3994
1679
  d_solveIntAttempts = 0;
3995
1679
}
3996
3997
bool TheoryArithPrivate::entireStateIsConsistent(const string& s){
3998
  bool result = true;
3999
  for(var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
4000
    ArithVar var = *vi;
4001
    //ArithVar var = d_partialModel.asArithVar(*i);
4002
    if(!d_partialModel.assignmentIsConsistent(var)){
4003
      d_partialModel.printModel(var);
4004
      Warning() << s << ":" << "Assignment is not consistent for " << var << d_partialModel.asNode(var);
4005
      if(d_tableau.isBasic(var)){
4006
        Warning() << " (basic)";
4007
      }
4008
      Warning() << endl;
4009
      result = false;
4010
    }else if(d_partialModel.isInteger(var) && !d_partialModel.integralAssignment(var)){
4011
      d_partialModel.printModel(var);
4012
      Warning() << s << ":" << "Assignment is not integer for integer variable " << var << d_partialModel.asNode(var);
4013
      if(d_tableau.isBasic(var)){
4014
        Warning() << " (basic)";
4015
      }
4016
      Warning() << endl;
4017
      result = false;
4018
    }
4019
  }
4020
  return result;
4021
}
4022
4023
bool TheoryArithPrivate::unenqueuedVariablesAreConsistent(){
4024
  bool result = true;
4025
  for(var_iterator vi = var_begin(), vend = var_end(); vi != vend; ++vi){
4026
    ArithVar var = *vi;
4027
    if(!d_partialModel.assignmentIsConsistent(var)){
4028
      if(!d_errorSet.inError(var)){
4029
4030
        d_partialModel.printModel(var);
4031
        Warning() << "Unenqueued var is not consistent for " << var <<  d_partialModel.asNode(var);
4032
        if(d_tableau.isBasic(var)){
4033
          Warning() << " (basic)";
4034
        }
4035
        Warning() << endl;
4036
        result = false;
4037
      } else if(Debug.isOn("arith::consistency::initial")){
4038
        d_partialModel.printModel(var);
4039
        Warning() << "Initial var is not consistent for " << var <<  d_partialModel.asNode(var);
4040
        if(d_tableau.isBasic(var)){
4041
          Warning() << " (basic)";
4042
        }
4043
        Warning() << endl;
4044
      }
4045
     }
4046
  }
4047
  return result;
4048
}
4049
4050
15250
void TheoryArithPrivate::presolve(){
4051
30500
  TimerStat::CodeTimer codeTimer(d_statistics.d_presolveTime);
4052
4053
15250
  d_statistics.d_initialTableauSize = d_tableau.size();
4054
4055
15250
  if(Debug.isOn("paranoid:check_tableau")){ d_linEq.debugCheckTableau(); }
4056
4057
  static thread_local unsigned callCount = 0;
4058
15250
  if(Debug.isOn("arith::presolve")) {
4059
    Debug("arith::presolve") << "TheoryArithPrivate::presolve #" << callCount << endl;
4060
    callCount = callCount + 1;
4061
  }
4062
4063
30500
  vector<TrustNode> lemmas;
4064
15250
  if (!options().base.incrementalSolving)
4065
  {
4066
7670
    switch (options().arith.arithUnateLemmaMode)
4067
    {
4068
      case options::ArithUnateLemmaMode::NO: break;
4069
      case options::ArithUnateLemmaMode::INEQUALITY:
4070
        d_constraintDatabase.outputUnateInequalityLemmas(lemmas);
4071
        break;
4072
      case options::ArithUnateLemmaMode::EQUALITY:
4073
        d_constraintDatabase.outputUnateEqualityLemmas(lemmas);
4074
        break;
4075
7670
      case options::ArithUnateLemmaMode::ALL:
4076
7670
        d_constraintDatabase.outputUnateInequalityLemmas(lemmas);
4077
7670
        d_constraintDatabase.outputUnateEqualityLemmas(lemmas);
4078
7670
        break;
4079
      default: Unhandled() << options().arith.arithUnateLemmaMode;
4080
    }
4081
  }
4082
4083
15250
  vector<TrustNode>::const_iterator i = lemmas.begin(), i_end = lemmas.end();
4084
89904
  for(; i != i_end; ++i){
4085
74654
    TrustNode lem = *i;
4086
37327
    Debug("arith::oldprop") << " lemma lemma duck " <<lem << endl;
4087
37327
    outputTrustedLemma(lem, InferenceId::ARITH_UNATE);
4088
  }
4089
15250
}
4090
4091
911019
EqualityStatus TheoryArithPrivate::getEqualityStatus(TNode a, TNode b) {
4092
911019
  if(d_qflraStatus == Result::SAT_UNKNOWN){
4093
    return EQUALITY_UNKNOWN;
4094
  }else{
4095
    try {
4096
911019
      if (getDeltaValue(a) == getDeltaValue(b)) {
4097
86207
        return EQUALITY_TRUE_IN_MODEL;
4098
      } else {
4099
824812
        return EQUALITY_FALSE_IN_MODEL;
4100
      }
4101
    } catch (DeltaRationalException& dr) {
4102
      return EQUALITY_UNKNOWN;
4103
    } catch (ModelException& me) {
4104
      return EQUALITY_UNKNOWN;
4105
    }
4106
  }
4107
}
4108
4109
1746
bool TheoryArithPrivate::propagateCandidateBound(ArithVar basic, bool upperBound){
4110
1746
  ++d_statistics.d_boundComputations;
4111
4112
1746
  RowIndex ridx = d_tableau.basicToRowIndex(basic);
4113
3492
  DeltaRational bound = d_linEq.computeRowBound(ridx, upperBound, basic);
4114
4115
4504
  if((upperBound && d_partialModel.strictlyLessThanUpperBound(basic, bound)) ||
4116
2048
     (!upperBound && d_partialModel.strictlyGreaterThanLowerBound(basic, bound))){
4117
4118
    // TODO: "Policy point"
4119
    //We are only going to recreate the functionality for now.
4120
    //In the future this can be improved to generate a temporary constraint
4121
    //if none exists.
4122
    //Experiment with doing this every time or only when the new constraint
4123
    //implies an unknown fact.
4124
4125
1730
    ConstraintType t = upperBound ? UpperBound : LowerBound;
4126
1730
    ConstraintP bestImplied = d_constraintDatabase.getBestImpliedBound(basic, t, bound);
4127
4128
    // Node bestImplied = upperBound ?
4129
    //   d_apm.getBestImpliedUpperBound(basic, bound):
4130
    //   d_apm.getBestImpliedLowerBound(basic, bound);
4131
4132
1730
    if(bestImplied != NullConstraint){
4133
      //This should be stronger
4134
1272
      Assert(!upperBound || bound <= bestImplied->getValue());
4135
1272
      Assert(
4136
          !upperBound
4137
          || d_partialModel.lessThanUpperBound(basic, bestImplied->getValue()));
4138
4139
1272
      Assert(upperBound || bound >= bestImplied->getValue());
4140
1272
      Assert(upperBound
4141
             || d_partialModel.greaterThanLowerBound(basic,
4142
                                                     bestImplied->getValue()));
4143
      //slightly changed
4144
4145
      // ConstraintP c = d_constraintDatabase.lookup(bestImplied);
4146
      // Assert(c != NullConstraint);
4147
4148
1272
      bool assertedToTheTheory = bestImplied->assertedToTheTheory();
4149
1272
      bool canBePropagated = bestImplied->canBePropagated();
4150
1272
      bool hasProof = bestImplied->hasProof();
4151
4152
2544
      Debug("arith::prop") << "arith::prop" << basic
4153
1272
                           << " " << assertedToTheTheory
4154
1272
                           << " " << canBePropagated
4155
1272
                           << " " << hasProof
4156
1272
                           << endl;
4157
4158
1272
      if(bestImplied->negationHasProof()){
4159
        Warning() << "the negation of " <<  bestImplied << " : " << endl
4160
                  << "has proof " << bestImplied->getNegation() << endl
4161
                  << bestImplied->getNegation()->externalExplainByAssertions()
4162
                  << endl;
4163
      }
4164
4165
1272
      if(!assertedToTheTheory && canBePropagated && !hasProof ){
4166
232
        d_linEq.propagateBasicFromRow(bestImplied);
4167
        // I think this can be skipped if canBePropagated is true
4168
        //d_learnedBounds.push(bestImplied);
4169
232
        if(Debug.isOn("arith::prop")){
4170
          Debug("arith::prop") << "success " << bestImplied << endl;
4171
          d_partialModel.printModel(basic, Debug("arith::prop"));
4172
        }
4173
232
        return true;
4174
      }
4175
1040
      if(Debug.isOn("arith::prop")){
4176
        Debug("arith::prop") << "failed " << basic
4177
                             << " " << bound
4178
                             << " " << assertedToTheTheory
4179
                             << " " << canBePropagated
4180
                             << " " << hasProof << endl;
4181
        d_partialModel.printModel(basic, Debug("arith::prop"));
4182
      }
4183
    }
4184
16
  }else if(Debug.isOn("arith::prop")){
4185
    Debug("arith::prop") << "false " << bound << " ";
4186
    d_partialModel.printModel(basic, Debug("arith::prop"));
4187
  }
4188
1514
  return false;
4189
}
4190
4191
4434
void TheoryArithPrivate::propagateCandidate(ArithVar basic){
4192
4434
  bool success = false;
4193
4434
  RowIndex ridx = d_tableau.basicToRowIndex(basic);
4194
4195
  bool tryLowerBound =
4196
8480
    d_partialModel.strictlyAboveLowerBound(basic) &&
4197
8480
    d_linEq.rowLacksBound(ridx, false, basic) == NULL;
4198
4199
  bool tryUpperBound =
4200
8446
    d_partialModel.strictlyBelowUpperBound(basic) &&
4201
8446
    d_linEq.rowLacksBound(ridx, true, basic) == NULL;
4202
4203
4434
  if(tryLowerBound){
4204
1020
    success |= propagateCandidateLowerBound(basic);
4205
  }
4206
4434
  if(tryUpperBound){
4207
726
    success |= propagateCandidateUpperBound(basic);
4208
  }
4209
4434
  if(success){
4210
226
    ++d_statistics.d_boundPropagations;
4211
  }
4212
4434
}
4213
4214
2552
void TheoryArithPrivate::propagateCandidates(){
4215
5104
  TimerStat::CodeTimer codeTimer(d_statistics.d_boundComputationTime);
4216
4217
2552
  Debug("arith::prop") << "propagateCandidates begin" << endl;
4218
4219
2552
  Assert(d_candidateBasics.empty());
4220
4221
2552
  if(d_updatedBounds.empty()){ return; }
4222
4223
2552
  DenseSet::const_iterator i = d_updatedBounds.begin();
4224
2552
  DenseSet::const_iterator end = d_updatedBounds.end();
4225
9200
  for(; i != end; ++i){
4226
3324
    ArithVar var = *i;
4227
6648
    if (d_tableau.isBasic(var)
4228
4098
        && d_tableau.basicRowLength(var)
4229
774
               <= options().arith.arithPropagateMaxLength)
4230
    {
4231
702
      d_candidateBasics.softAdd(var);
4232
    }
4233
    else
4234
    {
4235
2622
      Tableau::ColIterator basicIter = d_tableau.colIterator(var);
4236
15002
      for(; !basicIter.atEnd(); ++basicIter){
4237
6190
        const Tableau::Entry& entry = *basicIter;
4238
6190
        RowIndex ridx = entry.getRowIndex();
4239
6190
        ArithVar rowVar = d_tableau.rowIndexToBasic(ridx);
4240
6190
        Assert(entry.getColVar() == var);
4241
6190
        Assert(d_tableau.isBasic(rowVar));
4242
12380
        if (d_tableau.getRowLength(ridx)
4243
6190
            <= options().arith.arithPropagateMaxLength)
4244
        {
4245
4576
          d_candidateBasics.softAdd(rowVar);
4246
        }
4247
      }
4248
    }
4249
  }
4250
2552
  d_updatedBounds.purge();
4251
4252
11420
  while(!d_candidateBasics.empty()){
4253
4434
    ArithVar candidate = d_candidateBasics.back();
4254
4434
    d_candidateBasics.pop_back();
4255
4434
    Assert(d_tableau.isBasic(candidate));
4256
4434
    propagateCandidate(candidate);
4257
  }
4258
2552
  Debug("arith::prop") << "propagateCandidates end" << endl << endl << endl;
4259
}
4260
4261
1091022
void TheoryArithPrivate::propagateCandidatesNew(){
4262
  /* Four criteria must be met for progagation on a variable to happen using a row:
4263
   * 0: A new bound has to have been added to the row.
4264
   * 1: The hasBoundsCount for the row must be "full" or be full minus one variable
4265
   *    (This is O(1) to check, but requires book keeping.)
4266
   * 2: The current assignment must be strictly smaller/greater than the current bound.
4267
   *    assign(x) < upper(x)
4268
   *    (This is O(1) to compute.)
4269
   * 3: There is a bound that is strictly smaller/greater than the current assignment.
4270
   *    assign(x) < c for some x <= c literal
4271
   *    (This is O(log n) to compute.)
4272
   * 4: The implied bound on x is strictly smaller/greater than the current bound.
4273
   *    (This is O(n) to compute.)
4274
   */
4275
4276
2182044
  TimerStat::CodeTimer codeTimer(d_statistics.d_boundComputationTime);
4277
1091022
  Debug("arith::prop") << "propagateCandidatesNew begin" << endl;
4278
4279
1091022
  Assert(d_qflraStatus == Result::SAT);
4280
1091022
  if(d_updatedBounds.empty()){ return; }
4281
1091022
  dumpUpdatedBoundsToRows();
4282
1091022
  Assert(d_updatedBounds.empty());
4283
4284
1091022
  if(!d_candidateRows.empty()){
4285
2056962
    UpdateTrackingCallback utcb(&d_linEq);
4286
1028481
    d_partialModel.processBoundsQueue(utcb);
4287
  }
4288
4289
20145148
  while(!d_candidateRows.empty()){
4290
9527063
    RowIndex candidate = d_candidateRows.back();
4291
9527063
    d_candidateRows.pop_back();
4292
9527063
    propagateCandidateRow(candidate);
4293
  }
4294
1091022
  Debug("arith::prop") << "propagateCandidatesNew end" << endl << endl << endl;
4295
}
4296
4297
16957380
bool TheoryArithPrivate::propagateMightSucceed(ArithVar v, bool ub) const{
4298
25742485
  int cmp = ub ? d_partialModel.cmpAssignmentUpperBound(v)
4299
25742485
    : d_partialModel.cmpAssignmentLowerBound(v);
4300
16957380
  bool hasSlack = ub ? cmp < 0 : cmp > 0;
4301
16957380
  if(hasSlack){
4302
8299315
    ConstraintType t = ub ? UpperBound : LowerBound;
4303
8299315
    const DeltaRational& a = d_partialModel.getAssignment(v);
4304
4305
8299315
    if(isInteger(v) && !a.isIntegral()){
4306
95274
      return true;
4307
    }
4308
4309
8204041
    ConstraintP strongestPossible = d_constraintDatabase.getBestImpliedBound(v, t, a);
4310
8204041
    if(strongestPossible == NullConstraint){
4311
5302328
      return false;
4312
    }else{
4313
2901713
      bool assertedToTheTheory = strongestPossible->assertedToTheTheory();
4314
2901713
      bool canBePropagated = strongestPossible->canBePropagated();
4315
2901713
      bool hasProof = strongestPossible->hasProof();
4316
4317
2901713
      return !assertedToTheTheory && canBePropagated && !hasProof;
4318
    }
4319
  }else{
4320
8658065
    return false;
4321
  }
4322
}
4323
4324
4301613
bool TheoryArithPrivate::attemptSingleton(RowIndex ridx, bool rowUp){
4325
4301613
  Debug("arith::prop") << "  attemptSingleton" << ridx;
4326
4327
  const Tableau::Entry* ep;
4328
4301613
  ep = d_linEq.rowLacksBound(ridx, rowUp, ARITHVAR_SENTINEL);
4329
4301613
  Assert(ep != NULL);
4330
4331
4301613
  ArithVar v = ep->getColVar();
4332
4301613
  const Rational& coeff = ep->getCoefficient();
4333
4334
  // 0 = c * v + \sum rest
4335
  // Suppose rowUp
4336
  // - c * v = \sum rest \leq D
4337
  // if c > 0, v \geq -D/c so !vUp
4338
  // if c < 0, v \leq -D/c so  vUp
4339
  // Suppose not rowUp
4340
  // - c * v = \sum rest \geq D
4341
  // if c > 0, v \leq -D/c so  vUp
4342
  // if c < 0, v \geq -D/c so !vUp
4343
4301613
  bool vUp = (rowUp == ( coeff.sgn() < 0));
4344
4345
4301613
  Debug("arith::prop") << "  " << rowUp << " " << v << " " << coeff << " " << vUp << endl;
4346
4301613
  Debug("arith::prop") << "  " << propagateMightSucceed(v, vUp) << endl;
4347
4348
4301613
  if(propagateMightSucceed(v, vUp)){
4349
612456
    DeltaRational dr = d_linEq.computeRowBound(ridx, rowUp, v);
4350
612456
    DeltaRational bound = dr / (- coeff);
4351
306228
    return tryToPropagate(ridx, rowUp, v, vUp, bound);
4352
  }
4353
3995385
  return false;
4354
}
4355
4356
1569520
bool TheoryArithPrivate::attemptFull(RowIndex ridx, bool rowUp){
4357
1569520
  Debug("arith::prop") << "  attemptFull" << ridx << endl;
4358
4359
3139040
  vector<const Tableau::Entry*> candidates;
4360
4361
9923674
  for(Tableau::RowIterator i = d_tableau.ridRowIterator(ridx); !i.atEnd(); ++i){
4362
8354154
    const Tableau::Entry& e =*i;
4363
8354154
    const Rational& c = e.getCoefficient();
4364
8354154
    ArithVar v = e.getColVar();
4365
8354154
    bool vUp = (rowUp == (c.sgn() < 0));
4366
8354154
    if(propagateMightSucceed(v, vUp)){
4367
108829
      candidates.push_back(&e);
4368
    }
4369
  }
4370
1569520
  if(candidates.empty()){ return false; }
4371
4372
  const DeltaRational slack =
4373
182550
    d_linEq.computeRowBound(ridx, rowUp, ARITHVAR_SENTINEL);
4374
91275
  bool any = false;
4375
91275
  vector<const Tableau::Entry*>::const_iterator i, iend;
4376
200104
  for(i = candidates.begin(), iend = candidates.end(); i != iend; ++i){
4377
108829
    const Tableau::Entry* ep = *i;
4378
108829
    const Rational& c = ep->getCoefficient();
4379
108829
    ArithVar v = ep->getColVar();
4380
4381
    // See the comment for attemptSingleton()
4382
108829
    bool activeUp = (rowUp == (c.sgn() > 0));
4383
108829
    bool vUb = (rowUp == (c.sgn() < 0));
4384
4385
217658
    const DeltaRational& activeBound = activeUp ?
4386
72291
      d_partialModel.getUpperBound(v):
4387
145367
      d_partialModel.getLowerBound(v);
4388
4389
217658
    DeltaRational contribution = activeBound * c;
4390
217658
    DeltaRational impliedBound = (slack - contribution)/(-c);
4391
4392
108829
    bool success = tryToPropagate(ridx, rowUp, v, vUb, impliedBound);
4393
108829
    any |= success;
4394
  }
4395
91275
  return any;
4396
}
4397
4398
415057
bool TheoryArithPrivate::tryToPropagate(RowIndex ridx, bool rowUp, ArithVar v, bool vUb, const DeltaRational& bound){
4399
4400
696795
  bool weaker = vUb ? d_partialModel.strictlyLessThanUpperBound(v, bound):
4401
696795
    d_partialModel.strictlyGreaterThanLowerBound(v, bound);
4402
415057
  if(weaker){
4403
304246
    ConstraintType t = vUb ? UpperBound : LowerBound;
4404
4405
304246
    ConstraintP implied = d_constraintDatabase.getBestImpliedBound(v, t, bound);
4406
304246
    if(implied != NullConstraint){
4407
173894
      return rowImplicationCanBeApplied(ridx, rowUp, implied);
4408
    }
4409
  }
4410
241163
  return false;
4411
}
4412
4413
100695
Node flattenImplication(Node imp){
4414
201390
  NodeBuilder nb(kind::OR);
4415
201390
  std::unordered_set<Node> included;
4416
201390
  Node left = imp[0];
4417
201390
  Node right = imp[1];
4418
4419
100695
  if(left.getKind() == kind::AND){
4420
453708
    for(Node::iterator i = left.begin(), iend = left.end(); i != iend; ++i) {
4421
353013
      if (!included.count((*i).negate()))
4422
      {
4423
353013
        nb << (*i).negate();
4424
353013
        included.insert((*i).negate());
4425
      }
4426
    }
4427
  }else{
4428
    if (!included.count(left.negate()))
4429
    {
4430
      nb << left.negate();
4431
      included.insert(left.negate());
4432
    }
4433
  }
4434
4435
100695
  if(right.getKind() == kind::OR){
4436
    for(Node::iterator i = right.begin(), iend = right.end(); i != iend; ++i) {
4437
      if (!included.count(*i))
4438
      {
4439
        nb << *i;
4440
        included.insert(*i);
4441
      }
4442
    }
4443
  }else{
4444
100695
    if (!included.count(right))
4445
    {
4446
100695
      nb << right;
4447
100695
      included.insert(right);
4448
    }
4449
  }
4450
4451
201390
  return nb;
4452
}
4453
4454
173894
bool TheoryArithPrivate::rowImplicationCanBeApplied(RowIndex ridx, bool rowUp, ConstraintP implied){
4455
173894
  Assert(implied != NullConstraint);
4456
173894
  ArithVar v = implied->getVariable();
4457
4458
173894
  bool assertedToTheTheory = implied->assertedToTheTheory();
4459
173894
  bool canBePropagated = implied->canBePropagated();
4460
173894
  bool hasProof = implied->hasProof();
4461
4462
347788
  Debug("arith::prop") << "arith::prop" << v
4463
173894
                       << " " << assertedToTheTheory
4464
173894
                       << " " << canBePropagated
4465
173894
                       << " " << hasProof
4466
173894
                       << endl;
4467
4468
4469
173894
  if( !assertedToTheTheory && canBePropagated && !hasProof ){
4470
268922
    ConstraintCPVec explain;
4471
134461
    ARITH_PROOF(d_farkasBuffer.clear());
4472
134461
    RationalVectorP coeffs = ARITH_NULLPROOF(&d_farkasBuffer);
4473
4474
    // After invoking `propegateRow`:
4475
    //   * coeffs[0] is for implied
4476
    //   * coeffs[i+1] is for explain[i]
4477
134461
    d_linEq.propagateRow(explain, ridx, rowUp, implied, coeffs);
4478
134461
    if (d_tableau.getRowLength(ridx) <= options().arith.arithPropAsLemmaLength)
4479
    {
4480
100695
      if (Debug.isOn("arith::prop::pf")) {
4481
        for (const auto & constraint : explain) {
4482
          Assert(constraint->hasProof());
4483
          constraint->printProofTree(Debug("arith::prop::pf"));
4484
        }
4485
      }
4486
201390
      Node implication = implied->externalImplication(explain);
4487
201390
      Node clause = flattenImplication(implication);
4488
201390
      std::shared_ptr<ProofNode> clausePf{nullptr};
4489
4490
100695
      if (isProofEnabled())
4491
      {
4492
        // We can prove this lemma from Farkas...
4493
31586
        std::vector<std::shared_ptr<ProofNode>> conflictPfs;
4494
        // Assume the negated getLiteral version of the implied constaint
4495
        // then rewrite it into proof normal form.
4496
15793
        conflictPfs.push_back(
4497
94758
            d_pnm->mkNode(PfRule::MACRO_SR_PRED_TRANSFORM,
4498
31586
                          {d_pnm->mkAssume(implied->getLiteral().negate())},
4499
31586
                          {implied->getNegation()->getProofLiteral()}));
4500
        // Add the explaination proofs.
4501
68575
        for (const auto constraint : explain)
4502
        {
4503
105564
          NodeBuilder nb;
4504
52782
          conflictPfs.push_back(constraint->externalExplainByAssertions(nb));
4505
        }
4506
        // Collect the farkas coefficients, as nodes.
4507
31586
        std::vector<Node> farkasCoefficients;
4508
15793
        farkasCoefficients.reserve(coeffs->size());
4509
15793
        auto nm = NodeManager::currentNM();
4510
15793
        std::transform(
4511
            coeffs->begin(),
4512
            coeffs->end(),
4513
            std::back_inserter(farkasCoefficients),
4514
84368
            [nm](const Rational& r) { return nm->mkConst<Rational>(r); });
4515
4516
        // Prove bottom.
4517
15793
        auto sumPf = d_pnm->mkNode(
4518
31586
            PfRule::MACRO_ARITH_SCALE_SUM_UB, conflictPfs, farkasCoefficients);
4519
15793
        auto botPf = d_pnm->mkNode(
4520
31586
            PfRule::MACRO_SR_PRED_TRANSFORM, {sumPf}, {nm->mkConst(false)});
4521
4522
        // Prove the conflict
4523
31586
        std::vector<Node> assumptions;
4524
15793
        assumptions.reserve(clause.getNumChildren());
4525
15793
        std::transform(clause.begin(),
4526
                       clause.end(),
4527
                       std::back_inserter(assumptions),
4528
85265
                       [](TNode r) { return r.negate(); });
4529
31586
        auto notAndNotPf = d_pnm->mkScope(botPf, assumptions);
4530
4531
        // Convert it to a clause
4532
31586
        auto orNotNotPf = d_pnm->mkNode(PfRule::NOT_AND, {notAndNotPf}, {});
4533
47379
        clausePf = d_pnm->mkNode(
4534
31586
            PfRule::MACRO_SR_PRED_TRANSFORM, {orNotNotPf}, {clause});
4535
4536
        // Output it
4537
31586
        TrustNode trustedClause = d_pfGen->mkTrustNode(clause, clausePf);
4538
15793
        outputTrustedLemma(trustedClause, InferenceId::ARITH_ROW_IMPL);
4539
      }
4540
      else
4541
      {
4542
84902
        outputLemma(clause, InferenceId::ARITH_ROW_IMPL);
4543
      }
4544
    }
4545
    else
4546
    {
4547
33766
      Assert(!implied->negationHasProof());
4548
33766
      implied->impliedByFarkas(explain, coeffs, false);
4549
33766
      implied->tryToPropagate();
4550
    }
4551
134461
    return true;
4552
  }
4553
4554
39433
  if(Debug.isOn("arith::prop")){
4555
    Debug("arith::prop")
4556
      << "failed " << v << " " << assertedToTheTheory << " "
4557
      << canBePropagated << " " << hasProof << " " << implied << endl;
4558
    d_partialModel.printModel(v, Debug("arith::prop"));
4559
  }
4560
39433
  return false;
4561
}
4562
4563
9527063
bool TheoryArithPrivate::propagateCandidateRow(RowIndex ridx){
4564
9527063
  BoundCounts hasCount = d_linEq.hasBoundCount(ridx);
4565
9527063
  uint32_t rowLength = d_tableau.getRowLength(ridx);
4566
4567
9527063
  bool success = false;
4568
  static int instance = 0;
4569
9527063
  ++instance;
4570
4571
19054126
  Debug("arith::prop")
4572
9527063
    << "propagateCandidateRow " << instance << " attempt " << rowLength << " " <<  hasCount << endl;
4573
4574
19054126
  if (rowLength >= options().arith.arithPropagateMaxLength
4575
11137138
      && Random::getRandom().pickWithProb(
4576
1610075
          1.0 - double(options().arith.arithPropagateMaxLength) / rowLength))
4577
  {
4578
337212
    return false;
4579
  }
4580
4581
9189851
  if(hasCount.lowerBoundCount() == rowLength){
4582
664858
    success |= attemptFull(ridx, false);
4583
8524993
  }else if(hasCount.lowerBoundCount() + 1 == rowLength){
4584
2257920
    success |= attemptSingleton(ridx, false);
4585
  }
4586
4587
9189851
  if(hasCount.upperBoundCount() == rowLength){
4588
904662
    success |= attemptFull(ridx, true);
4589
8285189
  }else if(hasCount.upperBoundCount() + 1 == rowLength){
4590
2043693
    success |= attemptSingleton(ridx, true);
4591
  }
4592
9189851
  return success;
4593
}
4594
4595
1091022
void TheoryArithPrivate::dumpUpdatedBoundsToRows(){
4596
1091022
  Assert(d_candidateRows.empty());
4597
1091022
  DenseSet::const_iterator i = d_updatedBounds.begin();
4598
1091022
  DenseSet::const_iterator end = d_updatedBounds.end();
4599
6176734
  for(; i != end; ++i){
4600
2542856
    ArithVar var = *i;
4601
2542856
    if(d_tableau.isBasic(var)){
4602
1434455
      RowIndex ridx = d_tableau.basicToRowIndex(var);
4603
1434455
      d_candidateRows.softAdd(ridx);
4604
    }else{
4605
1108401
      Tableau::ColIterator basicIter = d_tableau.colIterator(var);
4606
25480605
      for(; !basicIter.atEnd(); ++basicIter){
4607
12186102
        const Tableau::Entry& entry = *basicIter;
4608
12186102
        RowIndex ridx = entry.getRowIndex();
4609
12186102
        d_candidateRows.softAdd(ridx);
4610
      }
4611
    }
4612
  }
4613
1091022
  d_updatedBounds.purge();
4614
1091022
}
4615
4616
const BoundsInfo& TheoryArithPrivate::boundsInfo(ArithVar basic) const{
4617
  RowIndex ridx = d_tableau.basicToRowIndex(basic);
4618
  return d_rowTracking[ridx];
4619
}
4620
4621
8517
std::pair<bool, Node> TheoryArithPrivate::entailmentCheck(TNode lit, const ArithEntailmentCheckParameters& params, ArithEntailmentCheckSideEffects& out){
4622
  using namespace inferbounds;
4623
4624
  // l k r
4625
  // diff : (l - r) k 0
4626
8517
  Debug("arith::entailCheck") << "TheoryArithPrivate::entailmentCheck(" << lit << ")"<< endl;
4627
  Kind k;
4628
  int primDir;
4629
17034
  Rational lm, rm, dm;
4630
17034
  Node lp, rp, dp;
4631
17034
  DeltaRational sep;
4632
8517
  bool successful = decomposeLiteral(lit, k, primDir, lm, lp, rm, rp, dm, dp, sep);
4633
8517
  if(!successful) { return make_pair(false, Node::null()); }
4634
4635
8517
  if(dp.getKind() == CONST_RATIONAL){
4636
    Node eval = Rewriter::rewrite(lit);
4637
    Assert(eval.getKind() == kind::CONST_BOOLEAN);
4638
    // if true, true is an acceptable explaination
4639
    // if false, the node is uninterpreted and eval can be forgotten
4640
    return make_pair(eval.getConst<bool>(), eval);
4641
  }
4642
8517
  Assert(dm != Rational(0));
4643
8517
  Assert(primDir == 1 || primDir == -1);
4644
4645
8517
  int negPrim = -primDir;
4646
4647
8517
  int secDir = (k == EQUAL || k == DISTINCT) ? negPrim: 0;
4648
8517
  int negSecDir = (k == EQUAL || k == DISTINCT) ? primDir: 0;
4649
4650
  // primDir*[lm*( lp )] k primDir*[ [rm*( rp )] + sep ]
4651
  // primDir*[lm*( lp ) - rm*( rp ) ] k primDir*sep
4652
  // primDir*[dm * dp] k primDir*sep
4653
4654
17034
  std::pair<Node, DeltaRational> bestPrimLeft, bestNegPrimRight, bestPrimDiff, tmp;
4655
17034
  std::pair<Node, DeltaRational> bestSecLeft, bestNegSecRight, bestSecDiff;
4656
8517
  bestPrimLeft.first = Node::null(); bestNegPrimRight.first = Node::null(); bestPrimDiff.first = Node::null();
4657
8517
  bestSecLeft.first = Node::null(); bestNegSecRight.first = Node::null(); bestSecDiff.first = Node::null();
4658
4659
4660
4661
8517
  ArithEntailmentCheckParameters::const_iterator alg, alg_end;
4662
23454
  for( alg = params.begin(), alg_end = params.end(); alg != alg_end; ++alg ){
4663
16682
    const inferbounds::InferBoundAlgorithm& ibalg = *alg;
4664
4665
16682
    Debug("arith::entailCheck") << "entailmentCheck trying " << (inferbounds::Algorithms) ibalg.getAlgorithm() << endl;
4666
16682
    switch(ibalg.getAlgorithm()){
4667
    case inferbounds::None:
4668
      break;
4669
16682
    case inferbounds::Lookup:
4670
    case inferbounds::RowSum:
4671
      {
4672
        typedef void (TheoryArithPrivate::*EntailmentCheckFunc)(std::pair<Node, DeltaRational>&, int, TNode) const;
4673
4674
        EntailmentCheckFunc ecfunc =
4675
16682
          (ibalg.getAlgorithm() == inferbounds::Lookup)
4676
          ? (&TheoryArithPrivate::entailmentCheckBoundLookup)
4677
16682
          : (&TheoryArithPrivate::entailmentCheckRowSum);
4678
4679
16682
        (*this.*ecfunc)(tmp, primDir * lm.sgn(), lp);
4680
16682
        setToMin(primDir * lm.sgn(), bestPrimLeft, tmp);
4681
4682
16682
        (*this.*ecfunc)(tmp, negPrim * rm.sgn(), rp);
4683
16682
        setToMin(negPrim * rm.sgn(), bestNegPrimRight, tmp);
4684
4685
16682
        (*this.*ecfunc)(tmp, secDir * lm.sgn(), lp);
4686
16682
        setToMin(secDir * lm.sgn(), bestSecLeft, tmp);
4687
4688
16682
        (*this.*ecfunc)(tmp, negSecDir * rm.sgn(), rp);
4689
16682
        setToMin(negSecDir * rm.sgn(), bestNegSecRight, tmp);
4690
4691
16682
        (*this.*ecfunc)(tmp, primDir * dm.sgn(), dp);
4692
16682
        setToMin(primDir * dm.sgn(), bestPrimDiff, tmp);
4693
4694
16682
        (*this.*ecfunc)(tmp, secDir * dm.sgn(), dp);
4695
16682
        setToMin(secDir * dm.sgn(), bestSecDiff, tmp);
4696
      }
4697
16682
      break;
4698
    default:
4699
      Unhandled();
4700
    }
4701
4702
    // turn bounds on prim * left and -prim * right into bounds on prim * diff
4703
16682
    if(!bestPrimLeft.first.isNull() && !bestNegPrimRight.first.isNull()){
4704
      //  primDir*lm* lp <= primDir*lm*L
4705
      // -primDir*rm* rp <= -primDir*rm*R
4706
      // primDir*lm* lp -primDir*rm* rp <=  primDir*lm*L - primDir*rm*R
4707
      // primDir [lm* lp -rm* rp] <= primDir[lm*L - *rm*R]
4708
      // primDir [dm * dp] <= primDir[lm*L - *rm*R]
4709
      // primDir [dm * dp] <= primDir * dm * ([lm*L - *rm*R]/dm)
4710
3197
      tmp.second = ((bestPrimLeft.second * lm) - (bestNegPrimRight.second * rm)) / dm;
4711
3197
      tmp.first = (bestPrimLeft.first).andNode(bestNegPrimRight.first);
4712
3197
      setToMin(primDir, bestPrimDiff, tmp);
4713
    }
4714
4715
    // turn bounds on sec * left and sec * right into bounds on sec * diff
4716
16682
    if(secDir != 0 && !bestSecLeft.first.isNull() && !bestNegSecRight.first.isNull()){
4717
      //  secDir*lm* lp <= secDir*lm*L
4718
      // -secDir*rm* rp <= -secDir*rm*R
4719
      // secDir*lm* lp -secDir*rm* rp <=  secDir*lm*L - secDir*rm*R
4720
      // secDir [lm* lp -rm* rp] <= secDir[lm*L - *rm*R]
4721
      // secDir [dm * dp] <= secDir[lm*L - *rm*R]
4722
      // secDir [dm * dp] <= secDir * dm * ([lm*L - *rm*R]/dm)
4723
      tmp.second = ((bestSecLeft.second * lm) - (bestNegSecRight.second * rm)) / dm;
4724
      tmp.first = (bestSecLeft.first).andNode(bestNegSecRight.first);
4725
      setToMin(secDir, bestSecDiff, tmp);
4726
    }
4727
4728
16682
    switch(k){
4729
16638
    case LEQ:
4730
16638
      if(!bestPrimDiff.first.isNull()){
4731
4649
        DeltaRational d = (bestPrimDiff.second * dm);
4732
3197
        if((primDir > 0 && d <= sep) || (primDir < 0 && d >= sep) ){
4733
3490
          Debug("arith::entailCheck") << "entailmentCheck found "
4734
1745
                                      << primDir << "*" << dm << "*(" << dp<<")"
4735
1745
                                      << " <= " << primDir << "*" << dm << "*" << bestPrimDiff.second
4736
1745
                                      << " <= " << primDir << "*" << sep << endl
4737
1745
                                      << " by " << bestPrimDiff.first << endl;
4738
1745
          Assert(bestPrimDiff.second * (Rational(primDir) * dm)
4739
                 <= (sep * Rational(primDir)));
4740
1745
          return make_pair(true, bestPrimDiff.first);
4741
        }
4742
      }
4743
14893
      break;
4744
22
    case EQUAL:
4745
22
      if(!bestPrimDiff.first.isNull() && !bestSecDiff.first.isNull()){
4746
        // Is primDir [dm * dp] == primDir * sep entailed?
4747
        // Iff [dm * dp] == sep entailed?
4748
        // Iff dp == sep / dm entailed?
4749
        // Iff dp <= sep / dm and dp >= sep / dm entailed?
4750
4751
        // primDir [dm * dp] <= primDir * dm * U
4752
        // secDir [dm * dp] <= secDir * dm * L
4753
4754
        // Suppose primDir * dm > 0
4755
        // then secDir * dm < 0
4756
        //   dp >= (secDir * L) / secDir * dm
4757
        //   dp >= (primDir * L) / primDir * dm
4758
        //
4759
        //   dp <= U / dm
4760
        //   dp >= L / dm
4761
        //   dp == sep / dm entailed iff U == L == sep
4762
        // Suppose primDir * dm < 0
4763
        // then secDir * dm > 0
4764
        //   dp >= U / dm
4765
        //   dp <= L / dm
4766
        //   dp == sep / dm entailed iff U == L == sep
4767
        if(bestPrimDiff.second == bestSecDiff.second){
4768
          if(bestPrimDiff.second == sep){
4769
            return make_pair(true, (bestPrimDiff.first).andNode(bestSecDiff.first));
4770
          }
4771
        }
4772
      }
4773
      // intentionally fall through to DISTINCT case!
4774
      // entailments of negations are eager exit cases for EQUAL
4775
      CVC5_FALLTHROUGH;
4776
    case DISTINCT:
4777
44
      if(!bestPrimDiff.first.isNull()){
4778
        // primDir [dm * dp] <= primDir * dm * U < primDir * sep
4779
        if((primDir > 0 && (bestPrimDiff.second * dm  < sep)) ||
4780
           (primDir < 0 && (bestPrimDiff.second * dm  > sep))){
4781
          // entailment of negation
4782
          if(k == DISTINCT){
4783
            return make_pair(true, bestPrimDiff.first);
4784
          }else{
4785
            Assert(k == EQUAL);
4786
            return make_pair(false, Node::null());
4787
          }
4788
        }
4789
      }
4790
44
      if(!bestSecDiff.first.isNull()){
4791
        // If primDir [dm * dp] > primDir * sep, then this is not entailed.
4792
        // If primDir [dm * dp] >= primDir * dm * L > primDir * sep
4793
        // -primDir * dm * L < -primDir * sep
4794
        // secDir * dm * L < secDir * sep
4795
        if((secDir > 0 && (bestSecDiff.second * dm < sep)) ||
4796
           (secDir < 0 && (bestSecDiff.second * dm > sep))){
4797
          if(k == DISTINCT){
4798
            return make_pair(true, bestSecDiff.first);
4799
          }else{
4800
            Assert(k == EQUAL);
4801
            return make_pair(false, Node::null());
4802
          }
4803
        }
4804
      }
4805
4806
44
      break;
4807
    default:
4808
      Unreachable();
4809
      break;
4810
    }
4811
  }
4812
6772
  return make_pair(false, Node::null());
4813
}
4814
4815
25551
bool TheoryArithPrivate::decomposeTerm(Node term, Rational& m, Node& p, Rational& c){
4816
51102
  Node t = Rewriter::rewrite(term);
4817
25551
  if(!Polynomial::isMember(t)){
4818
    return false;
4819
  }
4820
4821
  // TODO Speed up
4822
51102
  preprocessing::util::ContainsTermITEVisitor ctv;
4823
25551
  if(ctv.containsTermITE(t)){
4824
    return false;
4825
  }
4826
4827
51102
  Polynomial poly = Polynomial::parsePolynomial(t);
4828
25551
  if(poly.isConstant()){
4829
8495
    c = poly.getHead().getConstant().getValue();
4830
8495
    p = mkRationalNode(Rational(0));
4831
8495
    m = Rational(1);
4832
8495
    return true;
4833
17056
  }else if(poly.containsConstant()){
4834
4148
    c = poly.getHead().getConstant().getValue();
4835
4148
    poly = poly.getTail();
4836
  }else{
4837
12908
    c = Rational(0);
4838
  }
4839
17056
  Assert(!poly.isConstant());
4840
17056
  Assert(!poly.containsConstant());
4841
4842
17056
  const bool intVars = poly.allIntegralVariables();
4843
4844
17056
  if(intVars){
4845
17056
    m = Rational(1);
4846
17056
    if(!poly.isIntegral()){
4847
      Integer denom = poly.denominatorLCM();
4848
      m /= denom;
4849
      poly = poly * denom;
4850
    }
4851
34112
    Integer g = poly.gcd();
4852
17056
    m *= g;
4853
17056
    poly = poly * Rational(1,g);
4854
17056
    Assert(poly.isIntegral());
4855
17056
    Assert(poly.leadingCoefficientIsPositive());
4856
  }else{
4857
    Assert(!intVars);
4858
    m = poly.getHead().getConstant().getValue();
4859
    poly = poly * m.inverse();
4860
    Assert(poly.leadingCoefficientIsAbsOne());
4861
  }
4862
17056
  p = poly.getNode();
4863
17056
  return true;
4864
}
4865
4866
103289
void TheoryArithPrivate::setToMin(int sgn, std::pair<Node, DeltaRational>& min, const std::pair<Node, DeltaRational>& e){
4867
103289
  if(sgn != 0){
4868
53375
    if(min.first.isNull() && !e.first.isNull()){
4869
14881
      min = e;
4870
38494
    }else if(!min.first.isNull() && !e.first.isNull()){
4871
3197
      if(sgn > 0 && min.second > e.second){
4872
        min = e;
4873
3197
      }else if(sgn < 0 &&  min.second < e.second){
4874
        min = e;
4875
      }
4876
    }
4877
  }
4878
103289
}
4879
4880
// std::pair<bool, Node> TheoryArithPrivate::entailmentUpperCheck(const Rational& lm, Node lp, const Rational& rm, Node rp, const DeltaRational& sep, const ArithEntailmentCheckParameters& params, ArithEntailmentCheckSideEffects& out){
4881
4882
//   Rational negRM = -rm;
4883
//   Node diff = NodeManager::currentNM()->mkNode(MULT, mkRationalConstan(lm), lp) + (negRM * rp);
4884
4885
//   Rational diffm;
4886
//   Node diffp;
4887
//   decompose(diff, diffm, diffNode);
4888
4889
4890
//   std::pair<Node, DeltaRational> bestUbLeft, bestLbRight, bestUbDiff, tmp;
4891
//   bestUbLeft = bestLbRight = bestUbDiff = make_pair(Node::Null(), DeltaRational());
4892
4893
//   return make_pair(false, Node::null());
4894
// }
4895
4896
/**
4897
 * Decomposes a literal into the form:
4898
 *   dir*[lm*( lp )] k dir*[ [rm*( rp )] + sep ]
4899
 *   dir*[dm* dp]  k dir *sep
4900
 *   dir is either 1 or -1
4901
 */
4902
8517
bool TheoryArithPrivate::decomposeLiteral(Node lit, Kind& k, int& dir, Rational& lm,  Node& lp, Rational& rm, Node& rp, Rational& dm, Node& dp, DeltaRational& sep){
4903
8517
  bool negated = (lit.getKind() == kind::NOT);
4904
17034
  TNode atom = negated ? lit[0] : lit;
4905
4906
17034
  TNode left = atom[0];
4907
17034
  TNode right = atom[1];
4908
4909
  // left : lm*( lp ) + lc
4910
  // right: rm*( rp ) + rc
4911
17034
  Rational lc, rc;
4912
8517
  bool success = decomposeTerm(left, lm, lp, lc);
4913
8517
  if(!success){ return false; }
4914
8517
  success = decomposeTerm(right, rm, rp, rc);
4915
8517
  if(!success){ return false; }
4916
4917
17034
  Node diff = Rewriter::rewrite(NodeManager::currentNM()->mkNode(kind::MINUS, left, right));
4918
17034
  Rational dc;
4919
8517
  success = decomposeTerm(diff, dm, dp, dc);
4920
8517
  Assert(success);
4921
4922
  // reduce the kind of the to not include literals
4923
  // GT, NOT LEQ
4924
  // GEQ, NOT LT
4925
  // LT, NOT GEQ
4926
  // LEQ, NOT LT
4927
8517
  Kind atomKind = atom.getKind();
4928
8517
  Kind normKind = negated ? negateKind(atomKind) : atomKind;
4929
4930
8517
  if(normKind == GEQ || normKind == GT){
4931
4148
    dir = -1;
4932
4148
    normKind = (normKind == GEQ) ? LEQ : LT;
4933
  }else{
4934
4369
    dir = 1;
4935
  }
4936
4937
17034
  Debug("arith::decomp") << "arith::decomp "
4938
8517
                         << lit << "(" << normKind << "*" << dir << ")"<< endl
4939
8517
                         << "  left:" << lc << " + " << lm << "*(" <<  lp << ") : " <<left << endl
4940
8517
                         << "  right:" << rc << " + " << rm << "*(" <<  rp << ") : " << right << endl
4941
8517
                         << "  diff: " << dc << " + " << dm << "*("<< dp <<"): " << diff << endl
4942
8517
                         << "  sep: " << sep << endl;
4943
4944
4945
  // k in LT, LEQ, EQUAL, DISEQUAL
4946
  // [dir*lm*( lp ) + dir*lc] k [dir*rm*( rp ) + dir*rc]
4947
17034
  Rational change = rc - lc;
4948
8517
  Assert(change == (-dc));
4949
  // [dir*lm*( lp )] k [dir*rm*( rp ) + dir*(rc - lc)]
4950
8517
  if(normKind == LT){
4951
4347
    sep = DeltaRational(change, Rational(-1));
4952
4347
    k = LEQ;
4953
  }else{
4954
4170
    sep = DeltaRational(change);
4955
4170
    k = normKind;
4956
  }
4957
  // k in LEQ, EQUAL, DISEQUAL
4958
  // dir*lm*( lp ) k [dir*rm*( rp )] + dir*(sep + d * delta)
4959
8517
  return true;
4960
}
4961
4962
/**
4963
 *  Precondition:
4964
 *   tp is a polynomial not containing an ite.
4965
 *   either tp is constant or contains no constants.
4966
 *  Post:
4967
 *    if tmp.first is not null, then
4968
 *      sgn * tp <= sgn * tmp.second
4969
 */
4970
51102
void TheoryArithPrivate::entailmentCheckBoundLookup(std::pair<Node, DeltaRational>& tmp, int sgn, TNode tp) const {
4971
51102
  tmp.first = Node::null();
4972
51102
  if(sgn == 0){ return; }
4973
4974
25617
  Assert(Polynomial::isMember(tp));
4975
25617
  if(tp.getKind() == CONST_RATIONAL){
4976
8495
    tmp.first = mkBoolNode(true);
4977
8495
    tmp.second = DeltaRational(tp.getConst<Rational>());
4978
17122
  }else if(d_partialModel.hasArithVar(tp)){
4979
12534
    Assert(tp.getKind() != CONST_RATIONAL);
4980
12534
    ArithVar v = d_partialModel.asArithVar(tp);
4981
12534
    Assert(v != ARITHVAR_SENTINEL);
4982
    ConstraintP c = (sgn > 0)
4983
18698
      ? d_partialModel.getUpperBoundConstraint(v)
4984
18698
      : d_partialModel.getLowerBoundConstraint(v);
4985
12534
    if(c != NullConstraint){
4986
712
      tmp.first = Constraint::externalExplainByAssertions({c});
4987
712
      tmp.second = c->getValue();
4988
    }
4989
  }
4990
}
4991
4992
48990
void TheoryArithPrivate::entailmentCheckRowSum(std::pair<Node, DeltaRational>& tmp, int sgn, TNode tp) const {
4993
48990
  tmp.first = Node::null();
4994
92306
  if(sgn == 0){ return; }
4995
24561
  if(tp.getKind() != PLUS){ return; }
4996
16298
  Assert(Polynomial::isMember(tp));
4997
4998
16298
  tmp.second = DeltaRational(0);
4999
21972
  NodeBuilder nb(kind::AND);
5000
5001
21972
  Polynomial p = Polynomial::parsePolynomial(tp);
5002
33294
  for(Polynomial::iterator i = p.begin(), iend = p.end(); i != iend; ++i) {
5003
44616
    Monomial m = *i;
5004
44616
    Node x = m.getVarList().getNode();
5005
27620
    if(d_partialModel.hasArithVar(x)){
5006
27576
      ArithVar v = d_partialModel.asArithVar(x);
5007
27576
      const Rational& coeff = m.getConstant().getValue();
5008
27576
      int dir = sgn * coeff.sgn();
5009
      ConstraintP c = (dir > 0)
5010
38898
        ? d_partialModel.getUpperBoundConstraint(v)
5011
38898
        : d_partialModel.getLowerBoundConstraint(v);
5012
27576
      if(c != NullConstraint){
5013
16996
        tmp.second += c->getValue() * coeff;
5014
16996
        c->externalExplainByAssertions(nb);
5015
      }else{
5016
        //failed
5017
10580
        return;
5018
      }
5019
    }else{
5020
      // failed
5021
44
      return;
5022
    }
5023
  }
5024
  // success
5025
5674
  tmp.first = nb;
5026
}
5027
5028
3786
ArithProofRuleChecker* TheoryArithPrivate::getProofChecker()
5029
{
5030
3786
  return &d_checker;
5031
}
5032
5033
}  // namespace arith
5034
}  // namespace theory
5035
29502
}  // namespace cvc5