Java Code Examples for kodkod.engine.Solution#instance()

The following examples show how to use kodkod.engine.Solution#instance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ALG195_1.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Usage: java examples.tptp.ALG195_1
 */
public static void main(String[] args) {

    try {

        final ALG195_1 model = new ALG195_1();
        final Solver solver = new Solver();
        solver.options().setSolver(SATFactory.MiniSat);
        final Formula f = model.axioms().and(model.co1().not());
        final Bounds b = model.bounds();
        // System.out.println(model.decls());
        // System.out.println(model.ax2ax7());
        // System.out.println(b);
        final Solution sol = solver.solve(f, b);
        if (sol.instance() == null) {
            System.out.println(sol);
        } else {
            System.out.println(sol.stats());
            model.display(sol.instance());
        }
    } catch (NumberFormatException nfe) {
        usage();
    }
}
 
Example 2
Source File: ALG197.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Usage: java examples.tptp.ALG197
 */
public static void main(String[] args) {

	try {

		final ALG197 model = new ALG197();
		final Solver solver = new Solver();
		solver.options().setSolver(SATFactory.MiniSat);
		final Formula f = model.checkCO1();
		final Bounds b = model.bounds();
		final Solution sol = solver.solve(f, b);
		if (sol.instance()==null) {
			System.out.println(sol);
		} else {
			System.out.println(sol.stats());
			model.display(sol.instance());
		}
	} catch (NumberFormatException nfe) {
		usage();
	}
}
 
Example 3
Source File: ALG195.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Usage: java examples.tptp.ALG195
 */
public static void main(String[] args) {

    try {

        final ALG195 model = new ALG195();
        final Solver solver = new Solver();
        solver.options().setSolver(SATFactory.MiniSat);
        final Formula f = model.checkCO1();
        final Bounds b = model.bounds();
        // System.out.println(model.decls());
        // System.out.println(model.ax2ax7());
        // System.out.println(b);
        final Solution sol = solver.solve(f, b);
        if (sol.instance() == null) {
            System.out.println(sol);
        } else {
            System.out.println(sol.stats());
            model.display(sol.instance());
        }
    } catch (NumberFormatException nfe) {
        usage();
    }
}
 
Example 4
Source File: MagicSeries.java    From kodkod with MIT License 6 votes vote down vote up
private void print(Solution sol, Solver s) { 
	if (sol.instance()==null)
		System.out.println(sol);
	else {
		System.out.println(sol.outcome());
		System.out.println(sol.stats());
		final Evaluator eval = new Evaluator(sol.instance(), s.options());
		final Relation r = Relation.unary("r");
		final TupleFactory f = sol.instance().universe().factory();
		for(Object atom : f.universe()) { 
			eval.instance().add(r,  f.setOf(atom));
			System.out.print(atom + "->" + eval.evaluate(r.join(el).sum()) + "; ");
		}
		System.out.println();
	}
}
 
Example 5
Source File: UCoreStats.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that the given core is unsatisfiable with respect to the given bounds.
 *
 * @return true if the core is correct; false otherwise
 */
static boolean checkCorrect(Set<Formula> core, Bounds bounds) {
    System.out.print("checking correctness ... ");
    final long start = System.currentTimeMillis();
    Solver solver = solver();
    solver.options().setSolver(SATFactory.MiniSat);
    final Solution sol = solver.solve(Formula.and(core), bounds);
    final long end = System.currentTimeMillis();
    if (sol.instance() == null) {
        System.out.println("correct (" + (end - start) + " ms).");
        return true;
    } else {
        System.out.println("incorrect! (" + (end - start) + " ms). The core is satisfiable:");
        System.out.println(sol);
        return false;
    }
}
 
Example 6
Source File: ConfigAssure.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * Usage: java examples.ConfigAssure <ipAddresses file> <subnets file>
 */
public static void main(String[] args) {
    if (args.length < 2)
        usage();
    try {
        final ConfigAssure ca = new ConfigAssure();
        final Solver solver = new Solver();
        solver.options().setBitwidth(32);
        solver.options().setSolver(SATFactory.MiniSat);

        final Formula formula = ca.requirements();
        final Bounds bounds = ca.bounds(args[0], args[1]);

        System.out.println("---explicit requirements (others are implicit in the bounds)---");
        System.out.println(PrettyPrinter.print(formula, 2));

        System.out.println("\n---solving with config files " + args[0] + " and " + args[1] + "---");

        final Solution sol = solver.solve(formula, bounds);

        System.out.println("\n---OUTCOME---");
        System.out.println(sol.outcome());

        System.out.println("\n---STATS---");
        System.out.println(sol.stats());

        if (sol.instance() != null) {
            System.out.println("\n---INSTANCE--");
            ca.display(sol.instance(), solver.options());
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        usage();
    }
}
 
Example 7
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private final void testCompOp(IntCompOperator op, IntExpression ei, IntExpression ej, int i, int j, boolean result) {
    final Formula e = ei.compare(op, ej);
    final Formula f = ei.eq(constant(i)).and(ej.eq(constant(j))).and(result ? e : e.not());
    final Solution s = solve(f);
    if (overflows(ei, i, 0) || overflows(ej, j, 0)) {
        assertNull(f.toString(), s.instance());
    } else {
        assertNotNull(f.toString(), s.instance());
        final Evaluator eval = new Evaluator(s.instance(), solver.options());
        assertFalse(result ^ eval.evaluate(e));
    }
}
 
Example 8
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private final void testBinOp(IntOperator op, IntExpression ei, IntExpression ej, int i, int j, int result, int realResult, int mask) {
    final IntExpression e = ei.compose(op, ej);
    final Formula f = ei.eq(constant(i)).and(ej.eq(constant(j))).and(e.eq(constant(result)));
    final Solution s = solve(f);
    Instance inst = s.instance();
    if (overflows(op, ei, ej, i, j, realResult)) {
        assertNull(f.toString(), inst);
    } else {
        assertNotNull(f.toString(), inst);
        final Evaluator eval = new Evaluator(inst, solver.options());
        assertEquals(f.toString(), result & mask, eval.evaluate(e) & mask);
    }
}
 
Example 9
Source File: RegressionTests.java    From kodkod with MIT License 5 votes vote down vote up
@Test
public final void testFelix_01032007() {
	List<String> atomlist = Arrays.asList(
			"-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "0",
			"1", "2", "3", "4", "5", "6", "7");

	Universe universe = new Universe(atomlist);
	TupleFactory factory = universe.factory();
	Bounds bounds = new Bounds(universe);

	bounds.boundExactly(-8,factory.range(factory.tuple("-8"),factory.tuple("-8")));
	bounds.boundExactly(-7,factory.range(factory.tuple("-7"),factory.tuple("-7")));
	bounds.boundExactly(-6,factory.range(factory.tuple("-6"),factory.tuple("-6")));
	bounds.boundExactly(-5,factory.range(factory.tuple("-5"),factory.tuple("-5")));
	bounds.boundExactly(-4,factory.range(factory.tuple("-4"),factory.tuple("-4")));
	bounds.boundExactly(-3,factory.range(factory.tuple("-3"),factory.tuple("-3")));
	bounds.boundExactly(-2,factory.range(factory.tuple("-2"),factory.tuple("-2")));
	bounds.boundExactly(-1,factory.range(factory.tuple("-1"),factory.tuple("-1")));
	bounds.boundExactly(0,factory.range(factory.tuple("0"),factory.tuple("0")));
	bounds.boundExactly(1,factory.range(factory.tuple("1"),factory.tuple("1")));
	bounds.boundExactly(2,factory.range(factory.tuple("2"),factory.tuple("2")));
	bounds.boundExactly(3,factory.range(factory.tuple("3"),factory.tuple("3")));
	bounds.boundExactly(4,factory.range(factory.tuple("4"),factory.tuple("4")));
	bounds.boundExactly(5,factory.range(factory.tuple("5"),factory.tuple("5")));
	bounds.boundExactly(6,factory.range(factory.tuple("6"),factory.tuple("6")));
	bounds.boundExactly(7,factory.range(factory.tuple("7"),factory.tuple("7")));

	Expression set=IntConstant.constant(8).toExpression();

	Solver solver = new Solver();
	solver.options().setSolver(SATFactory.DefaultSAT4J);
	solver.options().setBitwidth(4);
	solver.options().setIntEncoding(Options.IntEncoding.TWOSCOMPLEMENT);
	Solution sol = solver.solve(set.some(), bounds);

	Evaluator eval = new Evaluator(sol.instance(), solver.options());
	TupleSet ts = eval.evaluate(set);
	assertFalse(ts.size()==0);

}
 
Example 10
Source File: LatinSquare.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Usage: java examples.LatinSquare [order]
 */
public static void main(String[] args) {
	if (args.length < 1)
		usage();
	
	try {
		final int n = Integer.parseInt(args[0]);
		if (n < 1)
			usage();
		final LatinSquare model = new LatinSquare();
		final Solver solver = new Solver();
		solver.options().setSolver(SATFactory.MiniSat);
		solver.options().setSymmetryBreaking(n*n*n);
		final Formula f = model.latin().and(model.qg5()).and(model.idempotent());
		final Bounds b = model.bounds(n);
		System.out.println(f); 
		final Solution sol = solver.solve(f, b);
		if (sol.instance()==null) {
			System.out.println(sol);
		} else {
			System.out.println(sol.stats());
			final Iterator<Tuple> iter = sol.instance().tuples(model.square).iterator();
			for(int i = 0; i < n; i++) {
				for(int j = 0; j < n; j++) {
					System.out.print(iter.next().atom(2));
					System.out.print("\t");
				}
				System.out.println();
			}
		}
	} catch (NumberFormatException nfe) {
		usage();
	}
}
 
Example 11
Source File: SymmetryBreakingTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private Instance solve(Formula f, Bounds b) {

        final Solution sol = solver.solve(f, b);
        final Statistics stats = sol.stats();
        pVars = stats.primaryVariables();
        iVars = stats.variables() - pVars;
        clauses = stats.clauses();
        return sol.instance();

    }
 
Example 12
Source File: SymmetryBreakingTest.java    From kodkod with MIT License 5 votes vote down vote up
private Instance solve(Formula f, Bounds b) {
	
		final Solution sol = solver.solve(f, b);
		final Statistics stats = sol.stats();
		pVars = stats.primaryVariables();
		iVars = stats.variables() - pVars;
		clauses = stats.clauses();
		return sol.instance();
	
}
 
Example 13
Source File: OverflowEnumTest.java    From org.alloytools.alloy with Apache License 2.0 4 votes vote down vote up
@Override
protected void runTestForAll(Tester t) {
    GenericTester gt = (GenericTester) t;
    this.op1 = Relation.unary("a");
    this.op2 = Relation.unary("b");
    bounds = superBounds.clone();
    bounds.bound(op1, factory.noneOf(1), factory.allOf(1));
    bounds.bound(op2, factory.noneOf(1), factory.allOf(1));

    Formula goal = op1.one().and(op2.one()).and(ret.one());
    // goal = goal.and(ret.sum().eq(gt.kodkodOpExpr(op1.sum(), op2.sum())));
    goal = goal.and(ret.eq(gt.kodkodOpExpr(op1.sum(), op2.sum()).toExpression()));
    Set<Res> kkRes = new HashSet<Res>();
    Iterator<Solution> sols = solveAll(goal);
    while (sols.hasNext()) {
        Solution sol = sols.next();
        if (sol.unsat())
            break;
        Evaluator evaluator = new Evaluator(sol.instance());
        int ia = evalInt(evaluator, op1);
        int ib = evalInt(evaluator, op2);
        int ir = evalInt(evaluator, ret);
        kkRes.add(new Res(ia, ib, ir));
    }

    Set<Res> jRes = new HashSet<Res>();
    int min = min();
    int max = max();
    for (int i = min; i <= max; i++) {
        for (int j = min; j <= max; j++) {
            if (gt.skip(i, j))
                continue;
            int res = gt.exeJava(i, j);
            if (res < min || res > max)
                continue;
            jRes.add(new Res(i, j, res));
        }
    }

    assertEquals(kkRes, jRes);
}
 
Example 14
Source File: HOLSome4AllTest.java    From org.alloytools.alloy with Apache License 2.0 4 votes vote down vote up
protected int evalS(Solution sol) {
    Instance inst = sol.instance();
    TupleSet x = inst.tuples(inst.skolems().iterator().next());
    return (Integer) x.iterator().next().atom(0);
}
 
Example 15
Source File: HOLSome4AllTest.java    From org.alloytools.alloy with Apache License 2.0 4 votes vote down vote up
protected TupleSet eval(Solution sol, Expression e) {
    Evaluator ev = new Evaluator(sol.instance());
    return ev.evaluate(e);
}
 
Example 16
Source File: RegressionTests.java    From kodkod with MIT License 4 votes vote down vote up
@Test
public final void testFelix_03062008_2() {
	Relation x5 = Relation.unary("Role");
	Relation x6 = Relation.unary("Session");

	List<String> atomlist = Arrays.asList("Role$0", "Session$0", "Session$1");

	Universe universe = new Universe(atomlist);
	TupleFactory factory = universe.factory();
	Bounds bounds = new Bounds(universe);

	TupleSet x5_upper = factory.noneOf(1);
	x5_upper.add(factory.tuple("Role$0"));
	bounds.bound(x5, x5_upper);

	TupleSet x6_upper = factory.noneOf(1);
	x6_upper.add(factory.tuple("Session$0"));
	x6_upper.add(factory.tuple("Session$1"));
	bounds.bound(x6, x6_upper);

	Variable x11=Variable.unary("x_a");
	Decls x10=x11.oneOf(x6);
	Variable x15=Variable.unary("x_b");
	Decls x14=x15.oneOf(x5);
	Variable x17=Variable.unary("x_c");
	Decls x16=x17.oneOf(x5);
	Decls x13=x14.and(x16);
	Expression x20=x15.product(x17);
	Expression x19=x11.product(x20);
	Formula x18=x19.some();
	Formula x12=x18.forSome(x13);
	Formula x9=x12.forAll(x10);
	Formula x24=x5.some();
	Formula x23=x24.not();
	Formula x28=x5.eq(x5);
	Formula x29=x6.eq(x6);
	Formula x25=x28.and(x29);
	Formula x22=x23.and(x25);
	Formula x8=x9.and(x22).and(x5.no()).and(x6.no());

	Solver solver = new Solver();
	solver.options().setSolver(SATFactory.DefaultSAT4J);
	solver.options().setBitwidth(2);
	solver.options().setIntEncoding(Options.IntEncoding.TWOSCOMPLEMENT);
	solver.options().setSymmetryBreaking(20);
	solver.options().setSkolemDepth(2);

	System.out.flush();

	Solution sol = solver.solve(x8, bounds);
	Instance inst = sol.instance();
	assertNotNull(inst);


	for(Relation rel : inst.relations()) { 
		if (rel!=x5 && rel!=x6) {
			final TupleSet range = inst.tuples(x6).product(inst.tuples(x5));
			assertTrue(range.containsAll(inst.tuples(rel)));
		}
	}
}
 
Example 17
Source File: Hotel.java    From org.alloytools.alloy with Apache License 2.0 4 votes vote down vote up
/**
 * Usage: java examples.Hotel [scope]
 */
public static void main(String[] args) {
    if (args.length < 1)
        usage();

    try {
        final int n = Integer.parseInt(args[0]);
        if (n < 1)
            usage();
        final Hotel model = new Hotel();
        final Solver solver = new Solver();
        solver.options().setSolver(SATFactory.MiniSatProver);
        solver.options().setLogTranslation(1);

        final Formula f = model.checkNoBadEntry();
        final Bounds b = model.bounds(n);

        // System.out.println(PrettyPrinter.print(f, 2, 100));

        final Solution sol = solver.solve(f, b);
        System.out.println(sol);

        if (sol.instance() == null) {
            final Proof proof = sol.proof();
            System.out.println("top-level formulas: " + proof.log().roots().size());
            System.out.println("initial core: " + proof.highLevelCore().size());
            System.out.print("\nminimizing core ... ");
            final long start = System.currentTimeMillis();
            proof.minimize(new RCEStrategy(proof.log()));
            final Set<Formula> core = Nodes.minRoots(f, proof.highLevelCore().values());
            final long end = System.currentTimeMillis();
            System.out.println("done (" + (end - start) + " ms).");
            System.out.println("minimal core: " + core.size());
            for (Formula u : core) {
                System.out.println(PrettyPrinter.print(u, 2, 100));
            }
            checkMinimal(core, b);
        } else {
            System.out.println(sol);
        }
    } catch (NumberFormatException nfe) {
        usage();
    }
}
 
Example 18
Source File: ToyLists.java    From kodkod with MIT License 4 votes vote down vote up
/**
 * Usage: java examples.alloy.ToyLists <# of lists> <# of things> <id of assertion to check or 0 to just run the spec>
 */
public static void main(String[] args) { 
	if (args.length < 3)
		usage();
	try {
		final int l = Integer.parseInt(args[0]);
		final int t = Integer.parseInt(args[1]);
		final int a = Integer.parseInt(args[2]);
		final ToyLists model = new ToyLists();
		
		final Bounds b = model.bounds(l, t);
		final Solver solver = new Solver();
		solver.options().setSolver(SATFactory.MiniSatProver);
		solver.options().setLogTranslation(1);
		solver.options().setSymmetryBreaking(1000);
		
		final Formula f;
		switch(a) {
		case 0 : f = model.spec(); break;
		case 1 : f = model.spec().and(model.equivPrefix().not()); break;
		case 2 : f = model.spec().and(model.loneList().not()); break;
		case 3 : f = model.spec().and(model.transitivePrefixes().not()); break;
		case 4 : f = model.spec().and(model.acyclicity().not()); break;
		case 5 : f = model.spec().and(model.equivReflexivity().not()); break;
		default : usage(); throw new AssertionError("dead code");
		}
		
			
		final Solution sol = solver.solve(f, b);
		if (sol.instance()!=null) {
			System.out.println(sol);
		} else {
			System.out.println(sol.outcome());
			System.out.println(sol.stats());
			
			System.out.println("Top level formulas: " + sol.proof().log().roots().size());
			System.out.println("Initial core: " + sol.proof().highLevelCore().size());
			
			sol.proof().minimize(new AdaptiveRCEStrategy(sol.proof().log()) );
			
			System.out.println("Minimal core: " + sol.proof().highLevelCore().size());
			
			final Set<Formula> core = Nodes.allRoots(f, sol.proof().highLevelCore().values());
			
			for(Formula c : core ) { 
				System.out.println(c);
			}
			
			System.out.print("checking the core ... ");
			if (solver.solve(Formula.and(core), b).instance()==null) { 
				System.out.println("correct.");
			} else {
				System.out.println("incorrect!");
			}
		}

	} catch (NumberFormatException nfe) {
		usage();
	}  
}
 
Example 19
Source File: RegressionTests.java    From kodkod with MIT License 4 votes vote down vote up
@Test
public final void testFelix_02222008() {
	List<String> atomlist = Arrays.asList("X1", "X2", "X3");

	Universe universe = new Universe(atomlist);
	TupleFactory factory = universe.factory();
	Bounds bounds = new Bounds(universe);

	Relation x = Relation.unary("X");
	TupleSet x_upper = factory.noneOf(1);
	x_upper.add(factory.tuple("X1"));
	x_upper.add(factory.tuple("X2"));
	x_upper.add(factory.tuple("X3"));
	bounds.bound(x, x_upper);

	Variable a = Variable.unary("a");
	Variable b = Variable.unary("b");
	Variable c = Variable.unary("c");
	Formula goal = x.lone().not().and(b.union(c).eq(a).forSome(c.oneOf(x)).forAll(b.oneOf(x)).forSome(a.setOf(x)));

	Solver solver = new Solver();
	solver.options().setSolver(SATFactory.DefaultSAT4J);
	solver.options().setBitwidth(4);
	solver.options().setIntEncoding(Options.IntEncoding.TWOSCOMPLEMENT);
	solver.options().setSymmetryBreaking(0);
	solver.options().setSkolemDepth(2);

	Iterator<Solution> itr = solver.solveAll(goal, bounds);
	int sols = 0;
	while(itr.hasNext()) {
		Solution sol = itr.next();
		Instance inst = sol.instance();
		if (inst==null) break;
		sols++;

		for(Relation rel : inst.relations()) { 
			if (rel!=x) {
				if( rel.arity()==1) { // rel = a
					assertEquals(inst.tuples(x), inst.tuples(rel));
				} else { // rel = c
					final TupleSet dom = factory.noneOf(1);
					for(Tuple t : inst.tuples(rel)) { 
						dom.add(factory.tuple(t.atom(0)));
					}
					assertEquals(inst.tuples(x), dom);
				}
			}
		}
	}
	assertEquals(3, sols);
}
 
Example 20
Source File: Drivers.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public static Instance check(UniverseFactory uf,
		SATFactory sat,
		Pair<Formula, Pair<Formula, Formula>> answer)
		throws URISyntaxException {
	Formula qf = answer.fst;		
	if (answer.snd.fst != null) {
		qf = qf.and(answer.snd.fst);
	}

	Formula cf = answer.fst;
	if (answer.snd.snd != null) {
		cf = cf.and(answer.snd.snd);
	}
	
	Set<Relation> liveRelations = ASTUtils.gatherRelations(qf.and(cf));
			
	Bounds b = uf.boundUniverse(liveRelations);
	
	Solver solver = new Solver();
	solver.options().setSolver(sat);
	solver.options().setIntEncoding(IntEncoding.TWOSCOMPLEMENT);
	solver.options().setBitwidth(bitWidth);
	//solver.options().setSkolemDepth(-1);
	solver.options().setSymmetryBreaking(0);
	solver.options().setSharing(1);
	Formula f = Nodes.simplify(qf, b);

	if (DEBUG) System.err.println(f);
	
	Solution s = solver.solve(f, b);
	
	if (s.outcome() == Outcome.SATISFIABLE || s.outcome() == Outcome.TRIVIALLY_SATISFIABLE) {
		Instance instance = s.instance();
			
		if (DEBUG) System.err.println(instance);
		return instance;
	} else {
		if (answer.snd.snd != null) {				
			Solution diff = solver.solve(Nodes.simplify(cf, b), b);

			if (diff.sat()) {
				Evaluator eval = new Evaluator(diff.instance());

				for(Relation rl : diff.instance().relations()) {
					if ("extra_solutions".equals(rl.name()) || "missing_solutions".equals(rl.name())) {
						System.err.println(rl.name() + ":\n" + eval.evaluate(rl));
					}
				}
			}
		}
		return null;
	}
}