forked from pjt33/MiniSAT.cs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.cs
1403 lines (1189 loc) · 42.5 KB
/
solver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************************
MiniSat -- Copyright (c) 2003-2005, Niklas Een, Niklas Sorensson
MiniSatCS -- Copyright (c) 2006-2007 Michal Moskal
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N,
// so that they can be used as array indices.
using Var = System.Int32;
namespace MiniSatCS {
public class Solver {
#region lbool
// Lifted booleans:
// the problem is C# allows use of ~ on any enum type
// thefore ~lbool.True == lbool.False, but we also end up using
// two undef values
public enum lbool : sbyte {
True = 1,
False = -2,
Undef0 = 0,
Undef1 = -1
}
public const lbool l_True = lbool.True;
public const lbool l_False = lbool.False;
static lbool toLbool(bool v) { return v ? lbool.True : lbool.False; }
public static bool isUndef(lbool l)
{
return l != lbool.True && l != lbool.False;
}
#endregion
#region Literals
//=================================================================================================
// Variables, literals, clause IDs:
const int var_Undef = -1;
public struct Lit {
public int x;
//TODO we cannot do that, is that a problem?
//public Lit() : x(2*var_Undef) {} // (lit_Undef)
public Lit(Var var, bool sign) {
x = var + var + (sign ? 1 : 0);
}
public Lit(Var var) {
x = var + var;
}
public static Lit operator ~ (Lit p) { Lit q; q.x = p.x ^ 1; return q; }
public static bool operator == (Lit p, Lit q) { return index(p) == index(q); }
public static bool operator != (Lit p, Lit q) { return index(p) != index(q); }
public static bool operator < (Lit p, Lit q) { return index(p) < index(q); } // '<' guarantees that p, ~p are adjacent in the ordering.
public override string ToString()
{
return (sign(this) ? "-" : "") + "x" + var(this);
}
public override int GetHashCode()
{
return x;
}
public override bool Equals(object other)
{
if (other == null) return false;
if (other is Lit)
return (Lit)other == this;
return false;
}
}
static public bool sign (Lit p) { return (p.x & 1) != 0; }
static public int var (Lit p) { return p.x >> 1; }
static public int index (Lit p) { return p.x; } // A "toInt" method that guarantees small, positive integers suitable for array indexing.
//static Lit toLit (int i) { Lit p = new Lit(); p.x = i; return p; } // Inverse of 'index()'.
//static Lit unsign(Lit p) { Lit q = new Lit(); q.x = p.x & ~1; return q; }
//static Lit id (Lit p, bool sgn) { Lit q; q.x = p.x ^ (sgn ? 1 : 0); return q; }
static public Lit lit_Undef = new Lit(var_Undef, false); // \- Useful special constants.
//static Lit lit_Error = new Lit(var_Undef, true ); // /
#endregion
#region Clauses
//=================================================================================================
// Clause -- a simple class for representing a clause:
const int ClauseId_null = int.MinValue;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public class Clause {
Lit[] data;
bool is_learnt;
protected internal Clause(bool learnt, vec<Lit> ps) {
is_learnt = learnt;
this.data = new Lit[ps.size()];
for (int i = 0; i < ps.size(); i++) data[i] = ps[i];
}
public int size () { return data.Length; }
public bool learnt () { return is_learnt; }
public Lit this[int i]
{
get { return data[i]; }
set { data[i] = value; }
}
public float activity;
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (Lit l in data)
sb.Append(l).Append(", ");
sb.Append("]");
return sb.ToString();
}
public Lit[] GetData() { return data; }
}
protected virtual Clause Clause_new(bool learnt, vec<Lit> ps)
{
return new Clause(learnt, ps);
}
#endregion
#region Utilities
//=================================================================================================
// Random numbers:
// Returns a random float 0 <= x < 1. Seed must never be 0.
static double drand(ref double seed)
{
seed *= 1389796;
int q = (int)(seed / 2147483647);
seed -= (double)q * 2147483647;
return seed / 2147483647;
}
// Returns a random integer 0 <= x < size. Seed must never be 0.
static int irand(ref double seed, int size)
{
return (int)(drand(ref seed) * size);
}
//=================================================================================================
// Time and Memory:
static double cpuTime()
{
return (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
}
static long memUsed()
{
return GC.GetTotalMemory(false);
}
[Conditional("DEBUG")]
static public void assert(bool expr)
{
if (!expr)
throw new Exception("assertion violated");
}
// Just like 'assert()' but expression will be evaluated in the release version as well.
static void check(bool expr) { assert(expr); }
// Redfine if you want output to go somewhere else:
public static void reportf(string format, params object[] args)
{
System.Console.Write(format, args);
}
public static void debug(string format, params object[] args)
{
System.Console.WriteLine(format, args);
}
#endregion
#region Stats, params
public class SolverStats {
public long starts, decisions, propagations, conflicts;
public long clauses_literals, learnts_literals, max_literals, tot_literals;
}
public class SearchParams {
public double var_decay, clause_decay, random_var_freq; // (reasonable values are: 0.95, 0.999, 0.02)
public SearchParams() : this(1,1,0) { }
public SearchParams(SearchParams other) : this(other.var_decay, other.clause_decay, other.random_var_freq) { }
public SearchParams(double v, double c, double r) { var_decay = v; clause_decay = c;
random_var_freq = r; }
}
#endregion
#region VarOrder
public class VarOrder {
readonly protected vec<lbool> assigns; // var.val. Pointer to external assignment table.
readonly protected vec<double> activity; // var.act. Pointer to external activity table.
protected Heap heap;
double random_seed; // For the internal random number generator
public VarOrder(vec<lbool> ass, vec<double> act)
{
assigns = ass;
activity = act;
heap = new Heap(var_lt);
random_seed = 91648253;
}
bool var_lt (Var x, Var y) { return activity[x] > activity[y]; }
public virtual void newVar()
{
heap.setBounds(assigns.size());
heap.insert(assigns.size()-1);
}
// Called when variable increased in activity.
public virtual void update(Var x)
{
if (heap.inHeap(x))
heap.increase(x);
}
// Called when variable is unassigned and may be selected again.
public virtual void undo(Var x)
{
if (!heap.inHeap(x))
heap.insert(x);
}
public Lit select()
{
return select(0.0);
}
// Selects a new, unassigned variable (or 'var_Undef' if none exists).
public virtual Lit select(double random_var_freq)
{
// Random decision:
if (drand(ref random_seed) < random_var_freq && !heap.empty()){
Var next = irand(ref random_seed,assigns.size());
if (isUndef(assigns[next]))
return ~new Lit(next);
}
// Activity based decision:
while (!heap.empty()){
Var next = heap.getmin();
if (isUndef(assigns[next]))
return ~new Lit(next);
}
return lit_Undef;
}
}
#endregion
#region Solver state
bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
protected vec<Clause> clauses; // List of problem clauses.
protected vec<Clause> learnts; // List of learnt clauses.
double cla_inc; // Amount to bump next clause with.
double cla_decay; // INVERSE decay factor for clause activity: stores 1/decay.
public vec<double> activity; // A heuristic measurement of the activity of a variable.
double var_inc; // Amount to bump next variable with.
double var_decay; // INVERSE decay factor for variable activity: stores 1/decay. Use negative value for static variable order.
VarOrder order; // Keeps track of the decision variable order.
vec<vec<Clause>> watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
public vec<lbool> assigns; // The current assignments.
public vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made.
protected vec<int> trail_lim; // Separator indices for different decision levels in 'trail'.
protected vec<Clause> reason; // 'reason[var]' is the clause that implied the variables current value, or 'null' if none.
protected vec<int> level; // 'level[var]' is the decision level at which assignment was made.
vec<int> trail_pos; // 'trail_pos[var]' is the variable's position in 'trail[]'. This supersedes 'level[]' in some sense, and 'level[]' will probably be removed in future releases.
int root_level; // Level of first proper decision.
int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
int simpDB_assigns; // Number of top-level assignments since last execution of 'simplifyDB()'.
long simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplifyDB()'.
// Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which is used:
//
vec<lbool> analyze_seen;
vec<Lit> analyze_stack;
vec<Lit> analyze_toclear;
vec<Lit> addUnit_tmp;
vec<Lit> addBinary_tmp;
vec<Lit> addTernary_tmp;
#endregion
#region Main internal methods:
void analyzeFinal (Clause confl) { analyzeFinal(confl, false); }
bool enqueue (Lit fact) { return enqueue(fact, null); }
// Activity:
//
void varBumpActivity(Lit p) {
if (var_decay < 0) return; // (negative decay means static variable order -- don't bump)
if ( (activity[var(p)] += var_inc) > 1e100 ) varRescaleActivity();
order.update(var(p)); }
void varDecayActivity () { if (var_decay >= 0) var_inc *= var_decay; }
void claDecayActivity () { cla_inc *= cla_decay; }
// Operations on clauses:
//
void newClause(vec<Lit> ps) { newClause(ps, false); }
void claBumpActivity (Clause c) { if ( (c.activity += (float)cla_inc) > 1e20 ) claRescaleActivity(); }
protected void remove (Clause c) { remove(c, false); }
protected bool locked (Clause c){ return c == reason[var(c[0])]; }
int decisionLevel() { return trail_lim.size(); }
#endregion
#region Public interface
public Solver() {
clauses = new vec<Clause>();
learnts = new vec<Clause>();
activity = new vec<double>();
watches = new vec<vec<Clause>>();
assigns = new vec<lbool>();
trail_pos = new vec<int>();
trail = new vec<Lit>();
trail_lim = new vec<int>();
reason = new vec<Clause>();
level = new vec<int>();
analyze_seen = new vec<lbool>();
analyze_stack = new vec<Lit>();
analyze_toclear = new vec<Lit>();
addUnit_tmp = new vec<Lit>();
addBinary_tmp = new vec<Lit>();
addTernary_tmp = new vec<Lit>();
model = new vec<lbool>();
conflict = new vec<Lit>();
addUnit_tmp .growTo(2);
addBinary_tmp .growTo(2);
addTernary_tmp.growTo(3);
stats = new SolverStats();
ok = true;
cla_inc = 1;
cla_decay = 1;
var_inc = 1;
var_decay = 1;
order = createOrder();
qhead = 0;
simpDB_assigns = 0;
simpDB_props = 0;
default_parms = new SearchParams(0.95, 0.999, 0.02);
expensive_ccmin = true;
verbosity = 0;
progress_estimate= 0;
vec<Lit> dummy = new vec<Lit>(2,lit_Undef);
dummy.pop();
}
protected virtual VarOrder createOrder()
{
return new VarOrder(assigns, activity);
}
~Solver() {
for (int i = 0; i < learnts.size(); i++) remove(learnts[i], true);
for (int i = 0; i < clauses.size(); i++) if (clauses[i] != null) remove(clauses[i], true);
}
// Helpers: (semi-internal)
//
public lbool value(Var x) { return assigns[x]; }
public lbool value(Lit p) { return sign(p) ? ~assigns[var(p)] : assigns[var(p)]; }
public int nAssigns() { return trail.size(); }
public int nClauses() { return clauses.size(); } // (minor difference from MiniSat without the GClause trick: learnt binary clauses will be counted as original clauses)
public int nLearnts() { return learnts.size(); }
// Statistics: (read-only member variable)
//
public SolverStats stats;
// Mode of operation:
//
public SearchParams default_parms; // Restart frequency etc.
public bool expensive_ccmin; // Controls conflict clause minimization. TRUE by default.
public int verbosity; // Verbosity level. 0=silent, 1=some progress report, 2=everything
// Problem specification:
//
// public Var newVar ();
public int nVars () { return assigns.size(); }
public void addUnit (Lit p) { addUnit_tmp [0] = p; addClause (addUnit_tmp); }
public void addBinary (Lit p, Lit q) { addBinary_tmp [0] = p; addBinary_tmp [1] = q; addClause(addBinary_tmp); }
public void addTernary(Lit p, Lit q, Lit r) { addTernary_tmp[0] = p; addTernary_tmp[1] = q; addTernary_tmp[2] = r; addClause(addTernary_tmp); }
public void addClause (vec<Lit> ps) { newClause(ps); } // (used to be a difference between internal and external method...)
// Solving:
//
public bool okay() { return ok; } // FALSE means solver is in an conflicting state (must never be used again!)
//public void simplifyDB();
//public bool solve(vec<Lit> assumps);
public bool solve() { vec<Lit> tmp = new vec<Lit>(); return solve(tmp); }
public double progress_estimate; // Set by 'search()'.
public vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any).
public vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions), this vector represent the conflict clause expressed in the assumptions.
#endregion
#region Operations on clauses:
/*_________________________________________________________________________________________________
|
| newClause : (ps : const vec<Lit>&) (learnt : bool) . [void]
|
| Description:
| Allocate and add a new clause to the SAT solvers clause database. If a conflict is detected,
| the 'ok' flag is cleared and the solver is in an unusable state (must be disposed).
|
| Input:
| ps - The new clause as a vector of literals.
| learnt - Is the clause a learnt clause? For learnt clauses, 'ps[0]' is assumed to be the
| asserting literal. An appropriate 'enqueue()' operation will be performed on this
| literal. One of the watches will always be on this literal, the other will be set to
| the literal with the highest decision level.
|
| Effect:
| Activity heuristics are updated.
|________________________________________________________________________________________________@*/
vec<Lit> BasicClauseSimplification(vec<Lit> ps, bool copy)
{
vec<Lit> qs;
if (copy) {
qs = new vec<Lit>();
ps.copyTo(qs); // Make a copy of the input vector.
} else {
qs = ps;
}
Dictionary<Var, Lit> dict = new Dictionary<Var,Lit>(ps.size());
int ptr = 0;
for (int i = 0; i < qs.size(); i++) {
Lit l = qs[i];
Lit other;
Var v = var(l);
if (dict.TryGetValue(v, out other)) {
if (other == l) {} // already seen it
else return null; // other = ~l, so always satisfied
} else {
dict[v] = l;
qs[ptr++] = l;
}
}
qs.shrinkTo(ptr);
return qs;
}
void reorderByLevel(vec<Lit> ps)
{
int max = int.MinValue;
int max_at = -1;
int max2 = int.MinValue;
int max2_at = -1;
for (int i = 0; i < ps.size(); ++i)
{
int lev = level[var(ps[i])];
if (lev == -1) lev = int.MaxValue;
else if (value(ps[i]) == lbool.True) lev = int.MaxValue;
if (lev >= max) {
max2_at = max_at;
max2 = max;
max = lev;
max_at = i;
} else if (lev > max2) {
max2 = lev;
max2_at = i;
}
}
if (max_at == 0)
ps.swap(1, max2_at);
else if (max_at == 1)
ps.swap(0, max2_at);
else if (max2_at == 0)
ps.swap(1, max_at);
else if (max2_at == 1)
ps.swap(0, max_at);
else {
ps.swap(0, max_at);
ps.swap(1, max2_at);
}
}
protected void newClause(vec<Lit> ps_, bool learnt)
{
newClause(ps_, learnt, false, true);
}
protected void newClause(vec<Lit> ps_, bool learnt, bool theoryClause, bool copy)
{
if (!ok) return;
//foreach (Lit p in ps_) { Console.Write (" {0} ", p); } Console.WriteLine (" END");
vec<Lit> ps;
assert(!(learnt && theoryClause));
if (!learnt){
assert(theoryClause || decisionLevel() == 0);
vec<Lit> qs = BasicClauseSimplification(ps_, copy);
if (qs == null) return;
// Check if clause is satisfied:
for (int i = 0; i < qs.size(); i++){
if (level[var(qs[i])] == 0 && value(qs[i]) == l_True)
return; }
// Remove false literals:
{
int i, j;
for (i = j = 0; i < qs.size(); i++)
if (level[var(qs[i])] != 0 || value(qs[i]) != l_False)
qs[j++] = qs[i];
qs.shrink(i - j);
}
ps = qs;
} else
ps = ps_;
// 'ps' is now the (possibly) reduced vector of literals.
if (ps.size() == 0){
ok = false;
}else if (ps.size() == 1){
// NOTE: If enqueue takes place at root level, the assignment will be lost in incremental use (it doesn't seem to hurt much though).
//if (!enqueue(ps[0], GClause_new(Clause_new(learnt, ps))))
if (theoryClause) {
levelToBacktrack = 0;
cancelUntil(0);
}
Clause c = Clause_new(learnt || theoryClause, ps);
NewClauseCallback(c);
if (!enqueue(ps[0]))
ok = false;
}else{
if (theoryClause)
reorderByLevel(ps);
// Allocate clause:
Clause c = Clause_new(learnt || theoryClause, ps);
if (!learnt && !theoryClause) {
// Store clause:
clauses.push(c);
stats.clauses_literals += c.size();
} else {
if (learnt) {
// Put the second watch on the literal with highest decision level:
int max_i = 1;
int max = level[var(ps[1])];
for (int i = 2; i < ps.size(); i++)
if (level[var(ps[i])] > max) {
max = level[var(ps[i])];
max_i = i;
}
c[1] = ps[max_i];
c[max_i] = ps[1];
check(enqueue(c[0], c));
} else {
MoveBack(c[0], c[1]);
}
// Bumping:
claBumpActivity(c); // (newly learnt clauses should be considered active)
learnts.push(c);
stats.learnts_literals += c.size();
}
// Watch clause:
watches[index(~c[0])].push(c);
watches[index(~c[1])].push(c);
NewClauseCallback(c);
}
}
// Disposes a clauses and removes it from watcher lists. NOTE! Low-level; does NOT change the 'clauses' and 'learnts' vector.
//
void remove(Clause c, bool just_dealloc)
{
if (!just_dealloc){
removeWatch(watches[index(~c[0])], c);
removeWatch(watches[index(~c[1])], c);
}
if (c.learnt()) stats.learnts_literals -= c.size();
else stats.clauses_literals -= c.size();
//xfree(c);
}
// Can assume everything has been propagated! (esp. the first two literals are != l_False, unless
// the clause is binary and satisfied, in which case the first literal is true)
// Returns True if clause is satisfied (will be removed), False otherwise.
//
bool simplify(Clause c)
{
assert(decisionLevel() == 0);
for (int i = 0; i < c.size(); i++){
if (value(c[i]) == l_True)
return true;
}
return false;
}
#endregion
#region Minor methods
static bool removeWatch(vec<Clause> ws, Clause elem) // Pre-condition: 'elem' must exists in 'ws' OR 'ws' must be empty.
{
if (ws.size() == 0) return false; // (skip lists that are already cleared)
int j = 0;
for (; ws[j] != elem ; j++) assert(j < ws.size() - 1);
for (; j < ws.size()-1; j++) ws[j] = ws[j+1];
ws.pop();
return true;
}
// Creates a new SAT variable in the solver. If 'decision_var' is cleared, variable will not be
// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result).
//
public Var newVar() {
int index;
index = nVars();
watches .push(new vec<Clause>()); // (list for positive literal)
watches .push(new vec<Clause>()); // (list for negative literal)
reason .push(null);
assigns .push(lbool.Undef0);
level .push(-1);
trail_pos .push(-1);
activity .push(0);
order .newVar();
analyze_seen.push(0);
return index; }
// Returns FALSE if immediate conflict.
bool assume(Lit p) {
trail_lim.push(trail.size());
return enqueue(p); }
// Revert to the state at given level.
protected void cancelUntil(int level) {
CancelUntilCallback(level);
if (decisionLevel() > level){
for (int c = trail.size()-1; c >= trail_lim[level]; c--){
Var x = var(trail[c]);
assigns[x] = lbool.Undef0;
reason [x] = null;
order.undo(x); }
trail.shrink(trail.size() - trail_lim[level]);
trail_lim.shrink(trail_lim.size() - level);
qhead = trail.size(); } }
#endregion
#region Major methods:
/*_________________________________________________________________________________________________
|
| analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) . [void]
|
| Description:
| Analyze conflict and produce a reason clause.
|
| Pre-conditions:
| * 'out_learnt' is assumed to be cleared.
| * Current decision level must be greater than root level.
|
| Post-conditions:
| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'.
|
| Effect:
| Will undo part of the trail, upto but not beyond the assumption of the current decision level.
|________________________________________________________________________________________________@*/
void analyze(Clause confl, vec<Lit> out_learnt, out int out_btlevel)
{
vec<lbool> seen = analyze_seen;
int pathC = 0;
Lit p = lit_Undef;
AdditionalConflictAnalisis(confl.GetData(), confl);
// Generate conflict clause:
//
out_learnt.push(new Lit()); // (leave room for the asserting literal)
out_btlevel = 0;
int index = trail.size()-1;
//debug("start analyze");
do{
/*
debug(" loop analyze {0} {1} {2}\n", confl, p, p==lit_Undef ? -1 : level[var(p)]);
if (confl == null)
{
for (int i = trail.size()-1; i >= 0; i--)
debug(" {0} {1} {2} {3}\n", trail[i], seen[var(trail[i])],
level[var(trail[i])], reason[var(trail[i])]);
} */
assert(confl != null); // (otherwise should be UIP)
Clause c = confl;
if (c.learnt())
claBumpActivity(c);
for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){
Lit q = c[j];
if (seen[var(q)] == 0 && level[var(q)] > 0){
varBumpActivity(q);
seen[var(q)] = lbool.True;
if (level[var(q)] == decisionLevel())
pathC++;
else{
out_learnt.push(q);
out_btlevel = Math.Max(out_btlevel, level[var(q)]);
}
}
}
// Select next clause to look at:
while (seen[var(trail[index--])] == 0);
p = trail[index+1];
confl = reason[var(p)];
seen[var(p)] = 0;
pathC--;
}while (pathC > 0);
out_learnt[0] = ~p;
// Conflict clause minimization:
{
int i, j;
if (expensive_ccmin){
// Simplify conflict clause (a lot):
//
uint min_level = 0;
for (i = 1; i < out_learnt.size(); i++)
min_level |= (uint)(1 << (level[var(out_learnt[i])] & 31)); // (maintain an abstraction of levels involved in conflict)
analyze_toclear.clear();
for (i = j = 1; i < out_learnt.size(); i++)
if (reason[var(out_learnt[i])] == null || !analyze_removable(out_learnt[i], min_level))
out_learnt[j++] = out_learnt[i];
}else{
// Simplify conflict clause (a little):
//
analyze_toclear.clear();
for (i = j = 1; i < out_learnt.size(); i++){
Clause r = reason[var(out_learnt[i])];
if (r == null)
out_learnt[j++] = out_learnt[i];
else{
Clause c = r;
for (int k = 1; k < c.size(); k++)
if (seen[var(c[k])]==0 && level[var(c[k])] != 0){
out_learnt[j++] = out_learnt[i];
goto Keep; }
analyze_toclear.push(out_learnt[i]);
Keep: ;
}
}
}
// Clean up:
//
{
int jj;
for (jj = 0; jj < out_learnt.size() ; jj++) seen[var(out_learnt [jj])] = 0;
for (jj = 0; jj < analyze_toclear.size(); jj++) seen[var(analyze_toclear[jj])] = 0; // ('seen[]' is now cleared)
}
stats.max_literals += out_learnt.size();
out_learnt.shrink(i - j);
stats.tot_literals += out_learnt.size();
}
}
// Check if 'p' can be removed. 'min_level' is used to abort early if visiting literals at a level that cannot be removed.
//
bool analyze_removable(Lit p_, uint min_level)
{
assert(reason[var(p_)] != null);
analyze_stack.clear(); analyze_stack.push(p_);
int top = analyze_toclear.size();
while (analyze_stack.size() > 0){
assert(reason[var(analyze_stack.last())] != null);
Clause c = reason[var(analyze_stack.last())];
analyze_stack.pop();
for (int i = 1; i < c.size(); i++){
Lit p = c[i];
if (analyze_seen[var(p)]==0 && level[var(p)] != 0){
if (reason[var(p)] != null && ((1 << (level[var(p)] & 31)) & min_level) != 0){
analyze_seen[var(p)] = lbool.True;
analyze_stack.push(p);
analyze_toclear.push(p);
}else{
for (int j = top; j < analyze_toclear.size(); j++)
analyze_seen[var(analyze_toclear[j])] = 0;
analyze_toclear.shrink(analyze_toclear.size() - top);
return false;
}
}
}
}
analyze_toclear.push(p_);
return true;
}
/*_________________________________________________________________________________________________
|
| analyzeFinal : (confl : Clause*) (skip_first : bool) . [void]
|
| Description:
| Specialized analysis procedure to express the final conflict in terms of assumptions.
| 'root_level' is allowed to point beyond end of trace (useful if called after conflict while
| making assumptions). If 'skip_first' is TRUE, the first literal of 'confl' is ignored (needed
| if conflict arose before search even started).
|________________________________________________________________________________________________@*/
void analyzeFinal(Clause confl, bool skip_first)
{
// -- NOTE! This code is relatively untested. Please report bugs!
conflict.clear();
if (root_level == 0) return;
vec<lbool> seen = analyze_seen;
for (int i = skip_first ? 1 : 0; i < confl.size(); i++){
Var x = var(confl[i]);
if (level[x] > 0)
seen[x] = lbool.True;
}
int start = (root_level >= trail_lim.size()) ? trail.size()-1 : trail_lim[root_level];
for (int i = start; i >= trail_lim[0]; i--){
Var x = var(trail[i]);
if (seen[x]!=0){
Clause r = reason[x];
if (r == null){
assert(level[x] > 0);
conflict.push(~trail[i]);
}else{
Clause c = r;
for (int j = 1; j < c.size(); j++)
if (level[var(c[j])] > 0)
seen[var(c[j])] = lbool.True;
}
seen[x] = lbool.Undef0;
}
}
}
/*_________________________________________________________________________________________________
|
| enqueue : (p : Lit) (from : Clause*) . [bool]
|
| Description:
| Puts a new fact on the propagation queue as well as immediately updating the variable's value.
| Should a conflict arise, FALSE is returned.
|
| Input:
| p - The fact to enqueue
| from - [Optional] Fact propagated from this (currently) unit clause. Stored in 'reason[]'.
| Default value is null (no reason).
|
| Output:
| TRUE if fact was enqueued without conflict, FALSE otherwise.
|________________________________________________________________________________________________@*/
bool enqueue(Lit p, Clause from)
{
if (!isUndef(value(p))) {
return value(p) != l_False;
}else{
Var x = var(p);
assigns[x] = toLbool(!sign(p));
level [x] = decisionLevel();
trail_pos[x] = trail.size();
reason [x] = from;
trail.push(p);
return true;
}
}
/*_________________________________________________________________________________________________
|
| propagate : [void] . [Clause*]
|
| Description:
| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned,
| otherwise null. NOTE! This method has been optimized for speed rather than readability.
|
| Post-conditions:
| * the propagation queue is empty, even if there was a conflict.
|________________________________________________________________________________________________@*/
Clause propagate()
{
Clause confl = null;
while (qhead < trail.size()){
stats.propagations++;
simpDB_props--;
Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate.
vec<Clause> ws = watches[index(p)];
//GClause* i,* j, *end;
int i, j, end;
for (i = j = 0, end = i + ws.size(); i != end;){
Clause c = ws[i++];
// Make sure the false literal is data[1]:
Lit false_lit = ~p;
if (c[0] == false_lit)
{ c[0] = c[1]; c[1] = false_lit; }
assert(c[1] == false_lit);
// If 0th watch is true, then clause is already satisfied.
Lit first = c[0];
lbool val = value(first);
if (val == l_True){
ws[j++] = c;
}else{
// Look for new watch:
for (int k = 2; k < c.size(); k++)
if (value(c[k]) != l_False){
c[1] = c[k]; c[k] = false_lit;
watches[index(~c[1])].push(c);
goto FoundWatch; }
// Did not find watch -- clause is unit under assignment:
ws[j++] = c;
if (!enqueue(first, c)){
if (decisionLevel() == 0)
ok = false;
confl = c;
qhead = trail.size();
// Copy the remaining watches:
while (i < end)