This repository was archived by the owner on Jun 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMain.java
More file actions
978 lines (797 loc) · 28.1 KB
/
Copy pathMain.java
File metadata and controls
978 lines (797 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import minkodkod.*;
import org.sat4j.specs.ContradictionException;
import org.sat4j.specs.TimeoutException;
import kodkod.ast.*;
import kodkod.ast.visitor.*;
import kodkod.instance.*;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.fol2sat.TrivialFormulaException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.opts.BooleanOption;
import org.kohsuke.args4j.opts.FileOption;
import org.kohsuke.args4j.opts.IntOption;
import org.kohsuke.args4j.opts.StringOption;
class MIntArrayWrapper
{
private int hashCode;
private int[] theArray;
private int length;
MIntArrayWrapper(int[] theArray)
{
// Caller is obligated to make a COPY of the clause array passed by Kodkod.
this.theArray = theArray;
hashCode = Arrays.hashCode(theArray);
this.length = theArray.length;
}
public boolean equals(Object obj)
{
if(obj instanceof MIntArrayWrapper)
return Arrays.equals(theArray, ((MIntArrayWrapper)obj).theArray);
return false;
}
public int hashCode()
{
return hashCode;
}
public int size()
{
return length;
}
public int get(int index)
{
return theArray[index]; // no out of bounds protection
}
public int[] getArray()
{
return theArray;
}
public String toString()
{
StringBuffer result = new StringBuffer();
for(int ii=0;ii<size();ii++)
{
result.append(get(ii));
result.append(" ");
}
return result.toString();
}
}
/*class CNFSpy implements SATSolver
{
List<MIntArrayWrapper> clauses = new ArrayList<MIntArrayWrapper>();
SATSolver internalSolver;
SATFactory mySATFactory;
CNFSpy(SATFactory mySATFactory)
{
// Spy on Kodkod -- remember the clauses given.
internalSolver = mySATFactory.instance();
this.mySATFactory = mySATFactory;
}
@Override
public void free()
{
internalSolver.free();
clauses.clear();
}
@Override
public boolean addClause(int[] lits)
{
// "No reference to the specified array is kept, so it can be reused."
// (From Kodkod Java doc)
// Kodkod _does_ re-use, so we can't wrap lits directly; we need to copy first.
int[] litsCopy = Arrays.copyOf(lits, lits.length);
MIntArrayWrapper wrapper = new MIntArrayWrapper(litsCopy);
// MEnvironment.errorStream.println("ADDED CLAUSE after "+clauses.size()+" others. It was: "+Arrays.toString(litsCopy));
clauses.add(wrapper);
return internalSolver.addClause(lits);
}
public void printClauses()
{
int iClause = 0;
for(MIntArrayWrapper aClause : clauses)
{
System.out.println("Clause "+iClause+": "+Arrays.toString(aClause.getArray()));
iClause++;
}
}
public ISolver getEquivalentSAT4j()
throws ContradictionException
{
// Do not have access to the internal ISolver object that Kodkod keeps. But we can re-create.
ISolver result = SolverFactory.newDefault();
result.newVar(internalSolver.numberOfVariables());
// no!
//result.setExpectedNumberOfClauses(internalSolver.numberOfClauses());
result.setTimeout(36000); // 10 hrs (just in case)
for(MIntArrayWrapper aClause : clauses)
{
// swap if need the IConstr
//IConstr x = result.addClause(new VecInt(aClause.getArray()));
result.addClause(new VecInt(aClause.getArray()));
//PrintWriter pw = new PrintWriter(MEnvironment.errorStream);
//result.printInfos(pw, ":::: ");
//pw.flush();
//if(x == null)
//MEnvironment.errorStream.println("conv: "+x + " : "+aClause.toString());
// sometimes null, but not always
// taut, cont, or... unit?
}
return result;
}
public CNFSpy makeCopy()
{
// Copy this solver.
// Yes, that means internalSolver.addClause calls. :(
CNFSpy newSolver = new CNFSpy(mySATFactory);
newSolver.addVariables(internalSolver.numberOfVariables());
// Can't use the same clauses set. But we can use the same arrays (no need to *copy* each clause)
for(MIntArrayWrapper wrapper : clauses)
{
newSolver.clauses.add(wrapper);
newSolver.internalSolver.addClause(wrapper.getArray());
// DEBUG
// Is this lovely clause tautologous?
// slow for now
//for(int ii=0;ii<wrapper.size();ii++)
// for(int jj=ii+1;jj<wrapper.size();jj++)
// {
// if(Math.abs(wrapper.get(ii)) == Math.abs(wrapper.get(jj)))
// MEnvironment.errorStream.println("TAUT");
// }
}
return newSolver;
}
@Override
public void addVariables(int numVars) {
internalSolver.addVariables(numVars);
}
@Override
public int numberOfClauses() {
return internalSolver.numberOfClauses();
}
@Override
public int numberOfVariables() {
return internalSolver.numberOfVariables();
}
@Override
public boolean solve() throws SATAbortedException
{
return internalSolver.solve();
}
@Override
public boolean valueOf(int variable)
{
return internalSolver.valueOf(variable);
}
}
*/
/*class CNFSpyFactory extends SATFactory
{
private SATFactory mySATFactory;
CNFSpyFactory(SATFactory mySATFactory)
{
this.mySATFactory = mySATFactory;
}
@Override
public SATSolver instance()
{
return new CNFSpy(mySATFactory);
}
}*/
class FreeVariableCollectionV extends AbstractCollector<Variable> {
public HashSet<Variable> newSet() {
return new HashSet<Variable>();
}
public FreeVariableCollectionV() {
super(new HashSet<Node>());
}
public Set<Variable> visit(Variable v) {
if (cache.containsKey(v))
return lookup(v);
cached.add(v);
HashSet<Variable> tempset = new HashSet<Variable>();
tempset.add(v);
return cache(v, tempset);
}
public Set<Variable> visit(QuantifiedFormula qf) {
if (cache.containsKey(qf))
return lookup(qf);
cached.add(qf);
// What free variables appear inside this quantifier?
// Re-create the set because we may get an immutable singleton back, and we remove from it below.
Set<Variable> tempset = new HashSet<Variable>(qf.formula().accept(this));
// These variables are quantified in this scope.
// (Don't worry about re-quantification later, since Kodkod won't run
// vs. such a formula.)
for (Decl d : qf.decls())
{
tempset.remove(d.variable());
}
return cache(qf, tempset);
}
}
class FormulaStruct{
Formula fmla;
Bounds bounds;
public FormulaStruct(Formula fmla, Bounds bounds){
this.fmla = fmla;
this.bounds = bounds;
}
public Formula getFmla() {
return fmla;
}
public void setFmla(Formula fmla) {
this.fmla = fmla;
}
public Bounds getBounds() {
return bounds;
}
public void setBounds(Bounds bounds) {
this.bounds = bounds;
}
}
class OutputData{
/**
* A list to store times to generate minimal models.
*/
int[] minimalTime;
/**
* A list to store times to generate random models.
*/
int[] randomTime;
/**
* A list to store the number of SAT solving iterations for computing
* minimal models.
*/
int[] iterations;
/**
* The size of the lists.
*/
final int size;
OutputData(int size){
this.size = size;
minimalTime = new int[size];
randomTime = new int[size];
iterations = new int[size];
for(int i = 0; i < size; i++){
minimalTime[i] = 0;
randomTime[i] = 0;
iterations[i] = 0;
}
}
}
public class Main {
private static FormulaStruct formula0(){
// TN: very basic fmla
// Every element is in either r1 or r2, possibly both:
Relation r1 = Relation.unary("R1");
Relation r2 = Relation.unary("R2");
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
Formula f = Expression.UNIV.in(r1.union(r2));
Bounds b = new Bounds(u);
TupleFactory tfac = u.factory();
b.bound(r1, tfac.noneOf(1), tfac.allOf(1));
b.bound(r2, tfac.noneOf(1), tfac.allOf(1));
return new FormulaStruct(f, b);
}
private static FormulaStruct formula1(){
Variable x = Variable.unary("x");
Relation r1 = Relation.unary("R1");
Relation r2 = Relation.unary("R2");
Relation r3 = Relation.unary("R3");
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
Formula f = x.in(r1).or(x.in(r2)).and(x.in(r3)).forSome(x.oneOf(Expression.UNIV));
Bounds b = new Bounds(u);
TupleFactory tfac = u.factory();
b.bound(r1, tfac.noneOf(1), tfac.allOf(1));
b.bound(r2, tfac.noneOf(1), tfac.allOf(1));
b.bound(r3, tfac.noneOf(1), tfac.allOf(1));
return new FormulaStruct(f, b);
}
private static FormulaStruct formula2(int length){
Variable x = Variable.unary("x");
Variable y = Variable.unary("y");
Expression xy = x.product(y);
Expression yx = y.product(x);
Formula f = null;
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
TupleFactory tfac = u.factory();
Bounds b = new Bounds(u);
for(int i = 0; i < length; i++){
Relation r = Relation.binary("R" + i);
b.bound(r, tfac.noneOf(2), tfac.allOf(2));
Formula temp = xy.in(r).and(yx.in(r));
if(f == null)
f = temp;
else
f = f.or(temp);
}
f = f.forSome(x.oneOf(Expression.UNIV)).forSome(y.oneOf(Expression.UNIV));
return new FormulaStruct(f, b);
}
//Multiplication where variables interleave (This example is not that interesting!).
private static FormulaStruct formula3(int length){
int size = length;
Formula f = null;
Formula temp = null;
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
TupleFactory tfac = u.factory();
Bounds b = new Bounds(u);
ArrayList<Variable> xs = new ArrayList<Variable>();
ArrayList<Variable> ys = new ArrayList<Variable>();
for(int i = 0; i < size; i++){
xs.add(Variable.unary("x" + i));
ys.add(Variable.unary("y" + i));
}
Relation r = Relation.unary("R");
b.bound(r, tfac.noneOf(1), tfac.allOf(1));
for(int i = 0; i < size * 2; i++){
int min = (i < size) ? 0: i - size + 1;
int max = (i < size) ? i: size - 1;
int offset = i < size? 0: i - size + 1;
temp = null;
for(int j = min; j <= max; j++){
Formula t = xs.get(j).in(r).and(ys.get(max - j + offset).in(r));
temp = (temp == null) ? t: temp.or(t);
}
if(temp != null)
f = (f == null) ? temp: f.and(temp);
}
for(int i = 0; i < size; i++){
f = f.forSome(xs.get(i).oneOf(Expression.UNIV));
f = f.forSome(ys.get(i).oneOf(Expression.UNIV));
}
return new FormulaStruct(f, b);
}
//Multiplication where relations interleave.
private static FormulaStruct formula4(int length){
int size = length;
Formula f = null;
Formula temp = null;
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
TupleFactory tfac = u.factory();
Bounds b = new Bounds(u);
Variable x = Variable.unary("x");
Variable y = Variable.unary("y");
Expression xy = x.product(y);
ArrayList<ArrayList<Relation>> relations = new ArrayList<ArrayList<Relation>>();
for(int i = 0; i < size; i++){
ArrayList<Relation> relation = new ArrayList<Relation>();
relations.add(relation);
for(int j = 0; j < size; j++){
Relation r = Relation.binary("R" + i + "," + j);
relation.add(r);
b.bound(r, tfac.noneOf(2), tfac.allOf(2));
}
}
for(int i = 0; i < size * 2; i++){
int min = (i < size) ? 0: i - size + 1;
int max = (i < size) ? i: size - 1;
int offset = i < size? 0: i - size + 1;
temp = null;
for(int j = min; j <= max; j++){
Formula t = xy.in(relations.get(j).get(max - j + offset));
temp = (temp == null) ? t: temp.or(t);
}
if(temp != null)
f = (f == null) ? temp: f.and(temp);
}
f = f.forSome(x.oneOf(Expression.UNIV)).forSome(y.oneOf(Expression.UNIV));
return new FormulaStruct(f, b);
}
//Transitive Closure
private static FormulaStruct formula5(){
Variable x = Variable.unary("x");
Variable y = Variable.unary("y");
Variable z = Variable.unary("z");
Variable x1 = Variable.unary("x1");
Variable x2 = Variable.unary("x2");
Expression xy = x.product(y);
Expression xz = x.product(z);
Expression zy = z.product(y);
Expression x1x2 = x1.product(x2);
Relation r = Relation.binary("R");
Relation rTC = Relation.binary("R+");
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("a");
allPossibleAtoms.add("b");
allPossibleAtoms.add("c");
allPossibleAtoms.add("d");
Universe u = new Universe(allPossibleAtoms);
//Transitive closure
Formula f = xy.in(r).implies(xy.in(rTC)).forAll(x.oneOf(Expression.UNIV)).forAll(y.oneOf(Expression.UNIV))
.and((xz.in(r)).and(zy.in(rTC)).implies(xy.in(rTC)).
forAll(x.oneOf(Expression.UNIV)).
forAll(y.oneOf(Expression.UNIV)).
forAll(z.oneOf(Expression.UNIV))).
//The relation is not empty!
and(x1x2.in(r).forSome(x1.oneOf(Expression.UNIV)).forSome(x2.oneOf(Expression.UNIV)));
Bounds b = new Bounds(u);
TupleFactory tfac = u.factory();
//b.bound(r, tfac.noneOf(2), tfac.allOf(2));
b.bound(r, tfac.range(tfac.tuple(2, 1), tfac.tuple(2, 4)), tfac.allOf(2));
b.bound(rTC, tfac.noneOf(2), tfac.allOf(2));
return new FormulaStruct(f, b);
}
/**
* Builds a formula from the content of a SATLib example file.
* @param fileName is the address of the example file.
* @return a formula
*/
private static FormulaStruct exampleFormula(String fileName){
Variable x = Variable.unary("x");
ExampleLoader example = new ExampleLoader(fileName);
ArrayList<ArrayList<Integer>> data = example.getContent();
ArrayList<Relation> relations = new ArrayList<Relation>();
Set<String> allPossibleAtoms = new HashSet<String>();
allPossibleAtoms.add("element0");
allPossibleAtoms.add("element1");
Universe u = new Universe(allPossibleAtoms);
Bounds b = new Bounds(u);
TupleFactory tfac = u.factory();
Formula f = null;
//Building relations:
for(int i = 1; i <= example.getNumOfVars(); i++){
Relation r = Relation.unary("R" + i);
b.bound(r, tfac.noneOf(1), tfac.allOf(1));
relations.add(r);
}
for(int i = 0; i < data.size(); i++){
ArrayList<Integer> clause = data.get(i);
Formula clauseFormula;
clauseFormula = null;
for(int j = 0; j < clause.size(); j++){
int relation = clause.get(j);
boolean negation = relation < 0;
relation = (relation > 0)? relation: -relation;
if(!negation){
if(clauseFormula == null)
clauseFormula = x.in(relations.get(relation - 1));
else
clauseFormula = clauseFormula.or(x.in(relations.get(relation - 1)));
}
else{
if(clauseFormula == null)
clauseFormula = x.in(relations.get(relation - 1)).not();
else
clauseFormula = clauseFormula.or(x.in(relations.get(relation - 1)).not());
}
}
if(f == null)
f = clauseFormula;
else
f = f.and(clauseFormula);
}
f = f.forSome(x.oneOf(Expression.UNIV));
return new FormulaStruct(f, b);
}
/**
* Gets executed when parameter "-m formula" is passed to the program.
* @param optFormula parameter -f
* @param optAugmentation parameter -a
* @param optLength parameter -l
* @throws TimeoutException
* @throws ContradictionException
*/
private static void formulaMode(IntOption optFormula,
BooleanOption optAugmentation, IntOption optLength)
throws TimeoutException, ContradictionException {
// Generating kodkod fmlas
if(!optFormula.isSet){
System.err.println("No formula specified.");
System.exit(0);
}
FormulaStruct fs = null;
switch (optFormula.value){
case 0: fs = formula0(); break;
case 1: fs = formula1(); break;
case 2: fs = formula2(optLength.value); break;
case 3: fs = formula3(optLength.value); break;
case 4: fs = formula4(optLength.value); break;
case 5: fs = formula5(); break;
}
Formula fmla = fs.getFmla();
Bounds b = fs.getBounds();
MinReporterToGatherSkolemBounds rep = new MinReporterToGatherSkolemBounds();
// Invoking the solver
MinSolver solver = new MinSolver();
solver.options().setFlatten(true);
solver.options().setSymmetryBreaking(0); // check we get 4 models not 2
MinSATSolverFactory minimalFactory = new MinSATSolverFactory(rep);
solver.options().setSolver(minimalFactory);
// tuple in upper bound ---> that tuple CAN appear in the relation
// tuple in lower bound ---> tuple MUST appear in the relation
solver.options().setReporter(rep);
// Ask for models of R(x) satisfying those bounds, over that universe.
// But kodkod only accepts SENTENCES. All vars must be bound:
Iterator<MinSolution> models = solver.solveAll(fmla, b);
int counter = 0;
while(models.hasNext())
{
long currTime = System.currentTimeMillis();
MinSolution model = models.next();
if(MinSolution.Outcome.UNSATISFIABLE.equals(model.outcome()) ||
MinSolution.Outcome.TRIVIALLY_UNSATISFIABLE.equals(model.outcome()))
break;
if(counter == 0)
{
System.out.println("========================================================");
System.out.println("FORMULA: " + fs.getFmla().toString());
System.out.println("Bounds: " + fs.getBounds().toString());
System.out.println("-------------------------------------------------------\n");
System.out.println("STATISTICS: ");
System.out.println(model.stats().clauses()+" clauses.");
System.out.println(model.stats().primaryVariables()+" primary variables.");
System.out.println(model.stats().variables()+" total variables.");
System.out.println(model.stats().translationTime()+" translation time.");
System.out.println("========================================================\n");
System.out.println("MODELS:");
}
// !!! question: how much of this delay in producing CFs is due to having to remove clauses?
System.out.println("Minimal model: "+model.instance().relationTuples());
System.out.println("Time to produce+print minimal model or UNSAT (ms): "+(System.currentTimeMillis()-currTime));
currTime = System.currentTimeMillis();
if(optAugmentation.isOn()){
Map<Relation, TupleSet> results = solver.getConsistentFacts(models).relationTuples();
Iterator<Relation> it1 = results.keySet().iterator();
while(it1.hasNext()){
Relation r = it1.next();
TupleSet tuples = results.get(r);
Iterator<Tuple> it2 = tuples.iterator();
while(it2.hasNext()){
Instance instance = new Instance(fs.bounds.universe());
TupleSet s = fs.bounds.universe().factory().setOf(it2.next());
instance.add(r, s);
System.out.println("-------------------------------------------------------");
System.out.println("Consistent Fact: " + instance.relationTuples());
System.out.println("Model: " + model.instance().relationTuples());
Iterator<MinSolution> augModels = null;
try{
augModels = solver.augment(fs.fmla, models, instance);
}
catch(ExplorationException e){
System.err.println(e.getMessage());
System.exit(0);
}
while(augModels.hasNext()){
MinSolution augModel = augModels.next();
if(MinSolution.Outcome.UNSATISFIABLE.equals(augModel.outcome()) ||
MinSolution.Outcome.TRIVIALLY_UNSATISFIABLE.equals(augModel.outcome()))
break;
System.out.println("Augmented model: " + augModel.instance().relationTuples());
}
}
}
//System.out.println("Augmentations: "+ solver.getConsistentFacts(models).relationTuples());
System.out.println("Time to produce+print augmentations (ms): "+(System.currentTimeMillis()-currTime));
}
System.out.println("========================================================\n");
counter++;
}
System.out.println("Total minimal models seen: "+counter);
}
/**
* Processing a single example file where "-m example".
* @param optInputFile the input file option.
* @param optOutputFile the output file option.
* @param optNumberOfModels the option corresponding to the number of models
* to generate.
*/
private static void exampleModeFile(FileOption optInputFile,
FileOption optOutputFile, IntOption optNumberOfModels) {
if(optInputFile.value == null){
System.err.println("No SATLib example file has been provided.");
System.exit(0);
}
int numberOfModels = 0;
if(optNumberOfModels.isSet)
numberOfModels = optNumberOfModels.value;
String inputFilePath = optInputFile.value.getAbsolutePath();
String outputFilePath = null;
if(optOutputFile.value != null)
outputFilePath = optOutputFile.value.getAbsolutePath();
else{
String fileName = optInputFile.value.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
fileName += ".dat";
outputFilePath = optInputFile.value.getParentFile().
getAbsolutePath() + File.separator + fileName;
}
exampleModeHelper(inputFilePath, outputFilePath, numberOfModels, null);
}
/**
* Processing the files in a directory where "-m example".
* @param optInputFile the input file option corresponding to the input directory.
* @param optOutputFile the output file option for the output directory.
* @param optNumberOfModels the option for the number of models to generate.
*/
private static void exampleModeDirectory(FileOption optInputFile,
FileOption optOutputFile, IntOption optNumberOfModels,
FileOption optSummaryFile) {
if(optInputFile.value == null){
System.err.println("No SATLib example file has been provided.");
System.exit(0);
}
if(optOutputFile.value != null){
if(!optOutputFile.value.isDirectory()){
System.err.println("The output has to be a path to a directory.");
System.exit(0);
}
}
int numberOfModels = 0;
if(optNumberOfModels.isSet)
numberOfModels = optNumberOfModels.value;
String outputFilePath = null;
if(optOutputFile.value != null)
outputFilePath = optOutputFile.value.getAbsolutePath();
else
outputFilePath = optInputFile.value.getAbsolutePath();
OutputData summary = null;
if(optSummaryFile.value != null)
summary = new OutputData(numberOfModels);
File files[] = optInputFile.value.listFiles();
for(int i = 0; i < files.length; i++){
String fileName = files[i].getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
fileName += ".dat";
System.out.print("Processing "+ files[i].getName() + "...");
exampleModeHelper(
files[i].getAbsolutePath(),
outputFilePath + File.separator + fileName,
numberOfModels, summary);
System.out.println("done!");
}
if(optSummaryFile.value != null){
//Writing the summary file:
try{
FileWriter fstream = new FileWriter(optSummaryFile.value);
BufferedWriter out = new BufferedWriter(fstream);
// Writing the header row:
out.write("iteration random minimal loops\n");
// Writing data rows:
for(int i = 1; i <= summary.size; i++){
out.write(i + " "
+ summary.randomTime[i - 1] + " "
+ summary.minimalTime[i - 1] + " "
+ summary.iterations[i - 1] + "\n");
}
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
/**
* Helper for example mode functions.
* @param inputFilePath the path of input example file.
* @param outputFilePath the path of output file.
* @param numberOfModels the number of models to generate.
* @param summary the input OutputData object to store a summary.
* @return the summary.
*/
private static OutputData exampleModeHelper(String inputFilePath,
String outputFilePath, int numberOfModels, OutputData summary) {
FormulaStruct fs = exampleFormula(inputFilePath);
Formula fmla = fs.getFmla();
Bounds bnds = fs.getBounds();
MinReporterToGatherSkolemBounds rep = new MinReporterToGatherSkolemBounds();
// Invoking the solver
MinSolver minSolver = new MinSolver();
minSolver.options().setFlatten(true);
//TODO parameterize symmetry breaking
minSolver.options().setSymmetryBreaking(0);
MinSATSolverFactory minimalFactory = new MinSATSolverFactory(rep);
minSolver.options().setSolver(minimalFactory);
Solver solver = new Solver();
solver.options().setFlatten(true);
solver.options().setSymmetryBreaking(0);
minSolver.options().setReporter(rep);
long currTime;
ArrayList<Long> randomModelTimes = new ArrayList<Long>();
ArrayList<Long> minimalModelTimes = new ArrayList<Long>();
ArrayList<Integer> minimalModelIterations = new ArrayList<Integer>();
Iterator<MinSolution> minModels = minSolver.solveAll(fmla, bnds);
//Generating minimal models:
while(minModels.hasNext()){
currTime = System.currentTimeMillis();
MinSolution sol = minModels.next();
minimalModelTimes.add(System.currentTimeMillis() - currTime);
minimalModelIterations.add(sol.minimizationHistory.SATSolverInvocations);
if(numberOfModels != 0){
if(minimalModelTimes.size() == numberOfModels)
break;
}
}
//Generating arbitrary models:
Iterator<Solution> models = solver.solveAll(fmla, bnds);
while(models.hasNext()){
currTime = System.currentTimeMillis();
models.next();
randomModelTimes.add(System.currentTimeMillis() - currTime);
if(randomModelTimes.size() == minimalModelTimes.size())
break;
}
//Writing the output file:
try{
FileWriter fstream = new FileWriter(outputFilePath);
BufferedWriter out = new BufferedWriter(fstream);
// Writing the header row:
out.write("iteration random minimal loops\n");
// Writing data rows:
for(int i = 1; i <= minimalModelTimes.size(); i++){
out.write(i + " "
+ randomModelTimes.get(i - 1) + " "
+ minimalModelTimes.get(i - 1) + " "
+ minimalModelIterations.get(i - 1) + "\n");
if(summary != null){
summary.minimalTime[i - 1] += minimalModelTimes.get(i - 1);
summary.randomTime[i - 1] += randomModelTimes.get(i - 1);
summary.iterations[i - 1] += minimalModelIterations.get(i - 1);
}
}
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
return summary;
}
/**
* The main method of the demo program.
*/
public static void main(String[] args) throws TrivialFormulaException, ContradictionException, TimeoutException {
//input formula ranging from 0 to 4.
IntOption optFormula = new IntOption("-f");
BooleanOption optAugmentation = new BooleanOption("-a");
IntOption optLength = new IntOption("-l", 10);
StringOption optMode = new StringOption("-m", "formula");
FileOption optInputFile = new FileOption("-i");
FileOption optOutputFile = new FileOption("-o");
IntOption optNumberOfModels = new IntOption("-n", 10);
FileOption optSummaryFile = new FileOption("-s");
CmdLineParser optParser = new CmdLineParser();
optParser.addOption(optMode);
optParser.addOption(optFormula);
optParser.addOption(optAugmentation);
optParser.addOption(optLength);
optParser.addOption(optInputFile);
optParser.addOption(optOutputFile);
optParser.addOption(optNumberOfModels);
optParser.addOption(optSummaryFile);
try{
optParser.parse(args);
}
catch(CmdLineException e){
System.err.println(e.getMessage());
}
if(optMode.value.equals("formula"))
formulaMode(optFormula, optAugmentation, optLength);
else{
if(optInputFile.value.isDirectory())
exampleModeDirectory(optInputFile, optOutputFile,
optNumberOfModels, optSummaryFile);
else
exampleModeFile(optInputFile, optOutputFile, optNumberOfModels);
}
}
}