Search in sources :

Example 1 with Instance

use of kodkod.instance.Instance in project org.alloytools.alloy by AlloyTools.

the class SkolemizationTest method testDeepSkolems.

public final void testDeepSkolems() {
    solver.options().setSkolemDepth(3);
    testDeepSkolems(Multiplicity.ONE);
    testDeepSkolems(Multiplicity.LONE);
    testDeepSkolems(Multiplicity.SOME);
    testDeepSkolems(Multiplicity.SET);
    final Variable va = Variable.unary("va");
    final Variable vb = Variable.unary("vb");
    Decl da1 = va.oneOf(r1a);
    Decl db = vb.oneOf(r1b);
    final Formula f0 = va.in(vb.join(r2b));
    final Formula f1 = f0.forAll(db).not().forAll(da1);
    final Formula f2 = f0.forSome(db).forSome(da1);
    Instance inst = solve(f1.and(f2));
    assertEquals(bounds.relations().size() + 3, inst.relations().size());
}
Also used : Formula(kodkod.ast.Formula) Variable(kodkod.ast.Variable) Instance(kodkod.instance.Instance) Decl(kodkod.ast.Decl)

Example 2 with Instance

use of kodkod.instance.Instance in project org.alloytools.alloy by AlloyTools.

the class Translation method interpret.

public Instance interpret(Bounds bounds) {
    final SATSolver solver = cnf();
    final Instance instance = new Instance(bounds.universe());
    final TupleFactory f = bounds.universe().factory();
    for (IndexedEntry<TupleSet> entry : bounds.intBounds()) {
        instance.add(entry.index(), entry.value());
    }
    for (Relation r : bounds.relations()) {
        // if (bnds != bounds && bnds.findRelByName(r.name()) == null)
        // continue;
        TupleSet lower = bounds.lowerBound(r);
        IntSet indices = Ints.bestSet(lower.capacity());
        indices.addAll(lower.indexView());
        IntSet vars = primaryVariables(r);
        if (!vars.isEmpty()) {
            // System.out.println(r + ": [" + vars.min() + ", " + vars.max()
            // + "]");
            int lit = vars.min();
            for (IntIterator iter = bounds.upperBound(r).indexView().iterator(); iter.hasNext(); ) {
                final int index = iter.next();
                if (!indices.contains(index) && solver.valueOf(lit++))
                    indices.add(index);
            }
        }
        instance.add(r, f.setOf(r.arity(), indices));
    }
    return instance;
}
Also used : SATSolver(kodkod.engine.satlab.SATSolver) TupleSet(kodkod.instance.TupleSet) Relation(kodkod.ast.Relation) IntIterator(kodkod.util.ints.IntIterator) Instance(kodkod.instance.Instance) IntSet(kodkod.util.ints.IntSet) TupleFactory(kodkod.instance.TupleFactory)

Example 3 with Instance

use of kodkod.instance.Instance in project org.alloytools.alloy by AlloyTools.

the class A4Solution method solve.

// ===================================================================================================//
/**
 * Solve for the solution if not solved already; if cmd==null, we will simply
 * use the lowerbound of each relation as its value.
 */
A4Solution solve(final A4Reporter rep, Command cmd, Simplifier simp, boolean tryBookExamples) throws Err, IOException {
    // If already solved, then return this object as is
    if (solved)
        return this;
    // the lower bound of each relation
    if (cmd == null) {
        Instance inst = new Instance(bounds.universe());
        for (int max = max(), i = min(); i <= max; i++) {
            Tuple it = factory.tuple("" + i);
            inst.add(i, factory.range(it, it));
        }
        for (Relation r : bounds.relations()) inst.add(r, bounds.lowerBound(r));
        eval = new Evaluator(inst, solver.options());
        rename(this, null, null, new UniqueNameGenerator());
        solved();
        return this;
    }
    // Otherwise, prepare to do the solve...
    final A4Options opt = originalOptions;
    long time = System.currentTimeMillis();
    rep.debug("Simplifying the bounds...\n");
    if (opt.inferPartialInstance && simp != null && formulas.size() > 0 && !simp.simplify(rep, this, formulas))
        addFormula(Formula.FALSE, Pos.UNKNOWN);
    rep.translate(opt.solver.id(), bitwidth, maxseq, solver.options().skolemDepth(), solver.options().symmetryBreaking());
    Formula fgoal = Formula.and(formulas);
    rep.debug("Generating the solution...\n");
    kEnumerator = null;
    Solution sol = null;
    final Reporter oldReporter = solver.options().reporter();
    final boolean[] solved = new boolean[] { true };
    solver.options().setReporter(new // Set up a
    AbstractReporter() {

        // reporter to
        // catch the
        // type+pos of
        // skolems
        @Override
        public void skolemizing(Decl decl, Relation skolem, List<Decl> predecl) {
            try {
                Type t = kv2typepos(decl.variable()).a;
                if (t == Type.EMPTY)
                    return;
                for (int i = (predecl == null ? -1 : predecl.size() - 1); i >= 0; i--) {
                    Type pp = kv2typepos(predecl.get(i).variable()).a;
                    if (pp == Type.EMPTY)
                        return;
                    t = pp.product(t);
                }
                kr2type(skolem, t);
            }// Exception here is not fatal
             catch (Throwable ex) {
            }
        }

        @Override
        public void solvingCNF(int primaryVars, int vars, int clauses) {
            if (solved[0])
                return;
            else
                // initially solved[0] is true, so we
                solved[0] = true;
            // won't report the # of vars/clauses
            if (rep != null)
                rep.solve(primaryVars, vars, clauses);
        }
    });
    if (!opt.solver.equals(SatSolver.CNF) && !opt.solver.equals(SatSolver.KK) && tryBookExamples) {
        // try
        // book
        // examples
        A4Reporter r = AlloyCore.isDebug() ? rep : null;
        try {
            sol = BookExamples.trial(r, this, fgoal, solver, cmd.check);
        } catch (Throwable ex) {
            sol = null;
        }
    }
    // this allows the reporter to report the # of
    solved[0] = false;
    // vars/clauses
    for (Relation r : bounds.relations()) {
        formulas.add(r.eq(r));
    }
    // Without this, kodkod refuses to grow unmentioned relations
    fgoal = Formula.and(formulas);
    // Now pick the solver and solve it!
    if (opt.solver.equals(SatSolver.KK)) {
        File tmpCNF = File.createTempFile("tmp", ".java", new File(opt.tempDirectory));
        String out = tmpCNF.getAbsolutePath();
        Util.writeAll(out, debugExtractKInput());
        rep.resultCNF(out);
        return null;
    }
    if (opt.solver.equals(SatSolver.CNF)) {
        File tmpCNF = File.createTempFile("tmp", ".cnf", new File(opt.tempDirectory));
        String out = tmpCNF.getAbsolutePath();
        solver.options().setSolver(WriteCNF.factory(out));
        try {
            sol = solver.solve(fgoal, bounds);
        } catch (WriteCNF.WriteCNFCompleted ex) {
            rep.resultCNF(out);
            return null;
        }
        // The formula is trivial (otherwise, it would have thrown an
        // exception)
        // Since the user wants it in CNF format, we manually generate a
        // trivially satisfiable (or unsatisfiable) CNF file.
        Util.writeAll(out, sol.instance() != null ? "p cnf 1 1\n1 0\n" : "p cnf 1 2\n1 0\n-1 0\n");
        rep.resultCNF(out);
        return null;
    }
    if (!solver.options().solver().incremental()) /*
                                                      * || solver.options().solver()==SATFactory. ZChaffMincost
                                                      */
    {
        if (sol == null)
            sol = solver.solve(fgoal, bounds);
    } else {
        kEnumerator = new Peeker<Solution>(solver.solveAll(fgoal, bounds));
        if (sol == null)
            sol = kEnumerator.next();
    }
    if (!solved[0])
        rep.solve(0, 0, 0);
    final Instance inst = sol.instance();
    // To ensure no more output during SolutionEnumeration
    solver.options().setReporter(oldReporter);
    // If unsatisfiable, then retreive the unsat core if desired
    if (inst == null && solver.options().solver() == SATFactory.MiniSatProver) {
        try {
            lCore = new LinkedHashSet<Node>();
            Proof p = sol.proof();
            if (sol.outcome() == UNSATISFIABLE) {
                // only perform the minimization if it was UNSATISFIABLE,
                // rather than TRIVIALLY_UNSATISFIABLE
                int i = p.highLevelCore().size();
                rep.minimizing(cmd, i);
                if (opt.coreMinimization == 0)
                    try {
                        p.minimize(new RCEStrategy(p.log()));
                    } catch (Throwable ex) {
                    }
                if (opt.coreMinimization == 1)
                    try {
                        p.minimize(new HybridStrategy(p.log()));
                    } catch (Throwable ex) {
                    }
                rep.minimized(cmd, i, p.highLevelCore().size());
            }
            for (Iterator<TranslationRecord> it = p.core(); it.hasNext(); ) {
                Object n = it.next().node();
                if (n instanceof Formula)
                    lCore.add((Formula) n);
            }
            Map<Formula, Node> map = p.highLevelCore();
            hCore = new LinkedHashSet<Node>(map.keySet());
            hCore.addAll(map.values());
        } catch (Throwable ex) {
            lCore = hCore = null;
        }
    }
    // If satisfiable, then add/rename the atoms and skolems
    if (inst != null) {
        eval = new Evaluator(inst, solver.options());
        rename(this, null, null, new UniqueNameGenerator());
    }
    // report the result
    solved();
    time = System.currentTimeMillis() - time;
    if (inst != null)
        rep.resultSAT(cmd, time, this);
    else
        rep.resultUNSAT(cmd, time, this);
    return this;
}
Also used : HybridStrategy(kodkod.engine.ucore.HybridStrategy) Instance(kodkod.instance.Instance) Node(kodkod.ast.Node) BinaryFormula(kodkod.ast.BinaryFormula) Formula(kodkod.ast.Formula) Relation(kodkod.ast.Relation) RCEStrategy(kodkod.engine.ucore.RCEStrategy) Solution(kodkod.engine.Solution) A4Reporter(edu.mit.csail.sdg.alloy4.A4Reporter) A4Reporter(edu.mit.csail.sdg.alloy4.A4Reporter) AbstractReporter(kodkod.engine.config.AbstractReporter) Reporter(kodkod.engine.config.Reporter) TranslationRecord(kodkod.engine.fol2sat.TranslationRecord) Decl(kodkod.ast.Decl) Evaluator(kodkod.engine.Evaluator) UniqueNameGenerator(edu.mit.csail.sdg.alloy4.UniqueNameGenerator) Type(edu.mit.csail.sdg.ast.Type) Proof(kodkod.engine.Proof) File(java.io.File) Tuple(kodkod.instance.Tuple)

Example 4 with Instance

use of kodkod.instance.Instance in project org.alloytools.alloy by AlloyTools.

the class BugTests method testGreg_01192006.

public final void testGreg_01192006() {
    // circular linked list
    Relation Entry = Relation.unary("Entry");
    Relation head = Relation.unary("head");
    Relation next = Relation.binary("next");
    Formula nextFun = next.function(Entry, Entry);
    // bijection between indices and entries in linked list
    Relation Index = Relation.unary("Index");
    Relation index2Entry = Relation.binary("index2Entry");
    Expression entries = head.join(next.closure());
    Variable e = Variable.unary("e");
    Expression preImage = index2Entry.join(e);
    Formula index2EntryBij = e.in(entries).implies(preImage.one()).and(e.in(entries).not().implies(preImage.no())).forAll(e.oneOf(Entry));
    // try to force list to have three distinct entries
    Variable e1 = Variable.unary("e1");
    Variable e2 = Variable.unary("e2");
    Variable e3 = Variable.unary("e3");
    Formula threeEntries = e1.eq(e2).not().and(e1.eq(e3).not()).and(e2.eq(e3).not()).forSome(e1.oneOf(entries).and(e2.oneOf(entries).and(e3.oneOf(entries))));
    Formula simulate = head.one().and(nextFun).and(index2EntryBij).and(threeEntries);
    Object Entry0 = "Entry0";
    Object Entry1 = "Entry1";
    Object Entry2 = "Entry2";
    Object Entry3 = "Entry3";
    Object Index0 = "Index0";
    Object Index1 = "Index1";
    Object Index2 = "Index2";
    Object Index3 = "Index3";
    Universe univ = new Universe(Arrays.asList(Entry0, Entry1, Entry2, Entry3, Index0, Index1, Index2, Index3));
    TupleFactory factory = univ.factory();
    TupleSet entryTuples = factory.setOf(Entry0, Entry1, Entry2, Entry3);
    TupleSet indexTuples = factory.setOf(Index0, Index1, Index2, Index3);
    Instance instance = new Instance(univ);
    instance.add(Entry, entryTuples);
    instance.add(head, factory.setOf(Entry0));
    instance.add(Index, indexTuples);
    Tuple next0 = factory.tuple(Entry0, Entry1);
    Tuple next1 = factory.tuple(Entry1, Entry2);
    Tuple next2 = factory.tuple(Entry2, Entry3);
    Tuple next3 = factory.tuple(Entry3, Entry0);
    instance.add(next, factory.setOf(next0, next1, next2, next3));
    Tuple i2e0 = factory.tuple(Index0, Entry0);
    Tuple i2e1 = factory.tuple(Index1, Entry1);
    Tuple i2e2 = factory.tuple(Index2, Entry2);
    Tuple i2e3 = factory.tuple(Index3, Entry3);
    instance.add(index2Entry, factory.setOf(i2e0, i2e1, i2e2, i2e3));
    Evaluator eval = new Evaluator(instance);
    assertTrue(eval.evaluate(simulate));
    Bounds bounds = new Bounds(univ);
    bounds.boundExactly(Entry, entryTuples);
    bounds.bound(head, entryTuples);
    bounds.bound(next, entryTuples.product(entryTuples));
    bounds.bound(Index, indexTuples);
    bounds.bound(index2Entry, indexTuples.product(entryTuples));
    // Solver solver = new Solver(SATSolverName.Default);
    // System.out.println(simulate);
    // System.out.println(bounds);
    // System.out.println(instance);
    instance = solver.solve(simulate, bounds).instance();
    // System.out.println(instance);
    assertNotNull(instance);
}
Also used : Formula(kodkod.ast.Formula) TupleSet(kodkod.instance.TupleSet) Relation(kodkod.ast.Relation) Variable(kodkod.ast.Variable) IntExpression(kodkod.ast.IntExpression) Expression(kodkod.ast.Expression) Instance(kodkod.instance.Instance) Bounds(kodkod.instance.Bounds) TupleFactory(kodkod.instance.TupleFactory) Universe(kodkod.instance.Universe) Evaluator(kodkod.engine.Evaluator) Tuple(kodkod.instance.Tuple)

Example 5 with Instance

use of kodkod.instance.Instance in project org.alloytools.alloy by AlloyTools.

the class BugTests method testVincent_02182006.

public final void testVincent_02182006() {
    // set ups universe of atoms [1..257]
    final List<Integer> atoms = new ArrayList<Integer>();
    // change this to 256, and the program works
    for (int i = 0; i < 257; i++) {
        atoms.add(i + 1);
    }
    final Universe universe = new Universe(atoms);
    final Bounds bounds = new Bounds(universe);
    final TupleFactory factory = universe.factory();
    final Relation oneRel = Relation.unary("oneRel");
    final Relation pCourses = Relation.binary("pCourses");
    final Relation prev = Relation.binary("prev");
    final Relation sCourses = Relation.binary("sCourses");
    final Relation prereqs = Relation.binary("prereqs");
    final Relation semester = Relation.unary("Semester");
    final Relation course = Relation.unary("Course");
    final Relation prereqset = Relation.unary("PrereqSet");
    final int courseIndex = 0;
    final int courseScope = 254;
    final int semesterIndex = 254;
    final int semesterScope = 2;
    final int prereqsetIndex = 256;
    final int prereqsetScope = 1;
    bounds.bound(course, factory.range(factory.tuple(atoms.get(courseIndex)), factory.tuple(atoms.get(courseIndex + courseScope - 1))));
    bounds.bound(semester, factory.range(factory.tuple(atoms.get(semesterIndex)), factory.tuple(atoms.get(semesterIndex + semesterScope - 1))));
    bounds.bound(prereqset, factory.range(factory.tuple(atoms.get(prereqsetIndex)), factory.tuple(atoms.get(prereqsetIndex + prereqsetScope - 1))));
    bounds.bound(oneRel, factory.setOf(factory.tuple(atoms.get(0))), factory.setOf(factory.tuple(atoms.get(0))));
    // list1 = [256, 2]
    // list2 = [256, 3]
    // pCoursesTS = [ [256, 2], [256, 3] ]
    List<Integer> list1 = new ArrayList<Integer>();
    list1.add(atoms.get(256));
    list1.add(atoms.get(1));
    List<Integer> list2 = new ArrayList<Integer>();
    list2.add(atoms.get(256));
    list2.add(atoms.get(2));
    TupleSet pCoursesTS = factory.setOf(factory.tuple(list1), factory.tuple(list2));
    bounds.bound(pCourses, pCoursesTS, pCoursesTS);
    // prevTS = [ [255, 254] ]
    TupleSet prevTS = factory.setOf(factory.tuple((Object) atoms.get(255), (Object) atoms.get(254)));
    bounds.bound(prev, prevTS, prevTS);
    // sCourses can be anything from Semester -> Course
    bounds.bound(sCourses, factory.area(factory.tuple((Object) atoms.get(semesterIndex), (Object) atoms.get(courseIndex)), factory.tuple((Object) atoms.get(semesterIndex + semesterScope - 1), (Object) atoms.get(courseIndex + courseScope - 1))));
    // pCoursesTS = [ [0, 256] ]
    TupleSet prereqsTS = factory.setOf(factory.tuple((Object) atoms.get(0), (Object) atoms.get(256)));
    bounds.bound(prereqs, prereqsTS, prereqsTS);
    // all s: futureSemesters | all c: s.courses | no c.prereqs or some p:
    // c.prereqs | p.courses in s.prev^.courses
    final Variable s = Variable.unary("s"), c = Variable.unary("c"), p = Variable.unary("p");
    Formula formula = (p.join(pCourses).in(s.join(prev.closure()).join(sCourses)).forAll(p.oneOf(c.join(prereqs)))).forAll(c.oneOf(s.join(sCourses))).forAll(s.oneOf(semester));
    // System.out.println(formula);
    final Instance instance = solver.solve(formula, bounds).instance();
    assertNotNull(instance);
}
Also used : TupleSet(kodkod.instance.TupleSet) Variable(kodkod.ast.Variable) Instance(kodkod.instance.Instance) Bounds(kodkod.instance.Bounds) ArrayList(java.util.ArrayList) TupleFactory(kodkod.instance.TupleFactory) Universe(kodkod.instance.Universe) Formula(kodkod.ast.Formula) Relation(kodkod.ast.Relation)

Aggregations

Instance (kodkod.instance.Instance)25 Formula (kodkod.ast.Formula)17 Relation (kodkod.ast.Relation)15 TupleFactory (kodkod.instance.TupleFactory)15 Universe (kodkod.instance.Universe)14 TupleSet (kodkod.instance.TupleSet)13 Bounds (kodkod.instance.Bounds)12 ArrayList (java.util.ArrayList)8 Variable (kodkod.ast.Variable)8 Evaluator (kodkod.engine.Evaluator)8 IntExpression (kodkod.ast.IntExpression)6 Solution (kodkod.engine.Solution)6 Expression (kodkod.ast.Expression)5 Tuple (kodkod.instance.Tuple)5 Decl (kodkod.ast.Decl)4 HashSet (java.util.HashSet)3 Solver (kodkod.engine.Solver)3 A4Reporter (edu.mit.csail.sdg.alloy4.A4Reporter)1 Err (edu.mit.csail.sdg.alloy4.Err)1 UniqueNameGenerator (edu.mit.csail.sdg.alloy4.UniqueNameGenerator)1