kodkod.ast.IntConstant Java Examples

The following examples show how to use kodkod.ast.IntConstant. 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: NQueens.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Prints the given solution
 */
void print(Instance instance, Options options) { 
	final Evaluator eval = new Evaluator(instance, options);
	for(int i = 0; i < n; i++) { 
		Expression ci = IntConstant.constant(i).toExpression();
		for(int j = 0; j < n; j++) { 
			Expression cj = IntConstant.constant(j).toExpression();
			if (eval.evaluate(x.join(ci).intersection(y.join(cj)).some())) { 
				System.out.print(" Q");
			} else {
				System.out.print(" .");
			}
		}
		System.out.println();
	}
}
 
Example #2
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
private void testIntSum(Options.IntEncoding encoding) {
    solver.options().setIntEncoding(encoding);
    final Variable x = Variable.unary("x");
    bounds.bound(r1, factory.setOf("13", "14", "15"), factory.setOf("13", "14", "15"));
    Formula f = IntConstant.constant(3).eq(IntConstant.constant(1).sum(x.oneOf(r1)));
    Solution s = solve(f);

    assertNotNull(s.instance());
    bounds.bound(r1, factory.noneOf(1), factory.setOf("1", "3", "5"));
    bounds.boundExactly(1, factory.setOf("1"));
    bounds.boundExactly(3, factory.setOf("3"));
    bounds.boundExactly(5, factory.setOf("5"));

    f = IntConstant.constant(9).eq(x.sum().sum(x.oneOf(r1)));
    s = solve(f);
    assertNotNull(s.instance());
    assertEquals(s.instance().tuples(r1), factory.setOf("1", "3", "5"));
}
 
Example #3
Source File: IncrementalOverflowNumTest.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() {
    Options opt = new Options();
    opt.setNoOverflow(true);
    opt.setBitwidth(2);
    IncrementalSolver solver = IncrementalSolver.solver(opt);
    Universe univ = new Universe("-2", "-1", "0", "1");
    Bounds b = new Bounds(univ);
    TupleFactory factory = univ.factory();
    b.boundExactly(-2, factory.range(factory.tuple("-2"), factory.tuple("-2")));
    b.boundExactly(-1, factory.range(factory.tuple("-1"), factory.tuple("-1")));
    b.boundExactly(0, factory.range(factory.tuple("0"), factory.tuple("0")));
    b.boundExactly(1, factory.range(factory.tuple("1"), factory.tuple("1")));
    Variable n = Variable.unary("n");
    Formula f = n.sum().plus(IntConstant.constant(1)).lte(n.sum()).forSome(n.oneOf(Expression.INTS));
    Solution sol = solver.solve(f, b);
    assertNoInstance(sol);
}
 
Example #4
Source File: IntTest.java    From kodkod with MIT License 6 votes vote down vote up
private void testIntSum(Options.IntEncoding encoding) {
	solver.options().setIntEncoding(encoding);
	final Variable x = Variable.unary("x");
	bounds.bound(r1, factory.setOf("13","14","15"), factory.setOf("13","14","15"));
	Formula f = IntConstant.constant(3).eq(IntConstant.constant(1).sum(x.oneOf(r1)));
	Solution s = solve(f);
	
	assertNotNull(s.instance());
	bounds.bound(r1, factory.noneOf(1), factory.setOf("1","3","5"));
	bounds.boundExactly(1, factory.setOf("1"));
	bounds.boundExactly(3, factory.setOf("3"));
	bounds.boundExactly(5, factory.setOf("5"));
	
	f = IntConstant.constant(9).eq(x.sum().sum(x.oneOf(r1)));
	s = solve(f);
	assertNotNull(s.instance());
	assertEquals(s.instance().tuples(r1), factory.setOf("1","3","5"));
}
 
Example #5
Source File: IntTest.java    From kodkod with MIT License 6 votes vote down vote up
@Test
public final void testExtremeShifts() {
	final int bw = 32;
	solver.options().setBitwidth(bw);
	final IntRange range = solver.options().integers();
	final int mask = ~(-1 << bw);
	final IntConstant min = IntConstant.constant(range.min());
	final IntConstant max = IntConstant.constant(range.max());
	testBinOp(SHL, min, min, min.value(), min.value(), 0, mask);
	testBinOp(SHL, min, max, min.value(), max.value(), 0, mask);
	testBinOp(SHL, max, min, max.value(), min.value(), 0, mask);
	testBinOp(SHL, max, max, max.value(), max.value(), 0, mask);
	testBinOp(SHA, min, min, min.value(), min.value(), -1, mask);
	testBinOp(SHA, min, max, min.value(), max.value(), -1, mask);
	testBinOp(SHA, max, min, max.value(), min.value(), 0, mask);
	testBinOp(SHA, max, max, max.value(), max.value(), 0, mask);
	testBinOp(SHR, min, min, min.value(), min.value(), 0, mask);
	testBinOp(SHR, min, max, min.value(), max.value(), 0, mask);
	testBinOp(SHR, max, min, max.value(), min.value(), 0, mask);
	testBinOp(SHR, max, max, max.value(), max.value(), 0, mask);
}
 
Example #6
Source File: TranslatorTest.java    From kodkod with MIT License 6 votes vote down vote up
@Test
public final void testTranslateProjection() {
	
	assertTrue(isSatisfiable(r3[0].eq(
			r2[0].project(IntConstant.constant(0), IntConstant.constant(1), IntConstant.constant(0)))));
	
	assertTrue(isSatisfiable(r2[1].in(r3[0].project(r1[3].count(), r1[2].count()))));

	final Variable v = Variable.nary("r", 2);
	assertFalse(isSatisfiable(v.transpose().
			eq(v.project(IntConstant.constant(1), IntConstant.constant(0))).not().
			forSome(v.setOf(r2[0]))));
	
	bounds.boundExactly(r3[0], bounds.upperBound(r3[0]));
	bounds.boundExactly(r2[0], bounds.upperBound(r2[0]));
	
	assertTrue(isSatisfiable(r3[0].project(IntConstant.constant(0), IntConstant.constant(1)).eq(r2[0])));
	assertTrue(isSatisfiable(r3[0].project(IntConstant.constant(0), IntConstant.constant(4), IntConstant.constant(2)).
			eq(Expression.NONE.product(Expression.NONE).product(Expression.NONE))));
	assertTrue(isSatisfiable(r3[0].project(IntConstant.constant(0), IntConstant.constant(-1), IntConstant.constant(2)).
			eq(Expression.NONE.product(Expression.NONE).product(Expression.NONE))));
	
}
 
Example #7
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static IntExpression floatCompare(IntExpression l, IntExpression r) {
	IntExpression ls = sign(l);
	IntExpression rs = sign(r);
	
	IntExpression le = exponent(l);
	IntExpression re = exponent(r);
	
	IntExpression lm = mantissa(l);
	IntExpression rm = mantissa(r);
	
	return
		threeWayTest(rs, ls,
			ls.eq(IntConstant.constant(0)).thenElse(
				threeWayTest(le, re,
					threeWayTest(lm, rm, zero)),
				threeWayTest(re, le,
					threeWayTest(rm, lm, zero))));
}
 
Example #8
Source File: Drivers.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static void run(String queryFile1, String queryFile2, boolean leftNonEmpty, boolean rightNonEmpty, int bound) throws URISyntaxException, MalformedURLException, IOException {
	UniverseFactory uf = new BoundedUniverse();

	Query q1 = JenaUtil.parse(queryFile1);
	Op query1 = JenaUtil.compile(q1);

	Query q2 = JenaUtil.parse(queryFile2);
	Op query2 = JenaUtil.compile(q2);

	JenaTranslator jt = JenaTranslator.make(q1.getProjectVars(), Arrays.asList(query1, query2), uf, null);
	Pair<Formula, Pair<Formula, Formula>> answer = jt.translateMulti(leftNonEmpty, rightNonEmpty);
	
	if (bound > 0) {
		answer = Pair.make(answer.fst.and(QuadTableRelations.quads.count().lte(IntConstant.constant(bound))), answer.snd);
	}
	
	if (DEBUG) System.err.println(answer.fst);
	
	check(uf, answer, "solution");
}
 
Example #9
Source File: IntConstraints.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the formula a1 <= v1 <= a2 <= v2 .... a1000<=v1000
 *
 * @return the formula
 */
public final Formula formula() {
    final List<Formula> constraints = new ArrayList<Formula>(2000);
    final List<IntConstant> constants = new ArrayList<IntConstant>(1001);
    for (int i = low; i <= high; i += 10) {
        constants.add(IntConstant.constant(i));
    }

    for (int i = 0; i < 1000; i++) {
        IntExpression varExpr = var[i].sum(); // convert to primitive int
        constraints.add(constants.get(i).lte(varExpr)); // a_i <= v_i
        constraints.add(varExpr.lte(constants.get(i + 1))); // v_i <=
                                                           // a_(i+1)
    }

    return Formula.and(constraints);
}
 
Example #10
Source File: Drivers.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static void runRepair(URL datasetURL, String queryFile, SparqlSelectResult result) throws URISyntaxException,
		MalformedURLException, ParserConfigurationException, SAXException,
		IOException 
{
	Query q = JenaUtil.parse(queryFile);
	List<Var> vars = q.getProjectVars();

	UniverseFactory uf = new ComparisonUniverse(datasetURL);

	SolutionRelation r = null;
	if (result != null) {
		uf.addSolution(r = new SolutionRelation(result, vars, Collections.<String,Object>emptyMap()));
	}

	Op query = JenaUtil.compile(q);
	JenaTranslator jt = r==null? JenaTranslator.make(vars, query, uf): JenaTranslator.make(vars, query, uf, r);
	Pair<Formula, Pair<Formula, Formula>> answer = jt.translateSingle(Collections.<String,Object>emptyMap(), false).iterator().next();

	Formula minDiff =
		QuadTableRelations.quads.union(QuadTableRelations.desiredQuads).count().minus(
			QuadTableRelations.quads.intersection(QuadTableRelations.desiredQuads).count()).lte(IntConstant.constant(1));
	
	answer = Pair.make(answer.fst.and(minDiff), Pair.make(answer.snd.fst.and(minDiff), answer.snd.snd.and(minDiff)));

	check(uf, answer, "solution");
}
 
Example #11
Source File: Transpose4x4UnaryLR.java    From kodkod with MIT License 6 votes vote down vote up
public Transpose4x4UnaryLR() {
	for(int i = 0; i < 4; i++) {
		sl[i] = Relation.unary("sl[" + i + "]");	
		tl[i] = Relation.unary("tl[" + i + "]");
		
		mx1[i] = Relation.unary("mx1[" + i + "]");
		mx2[i] = Relation.unary("mx2[" + i + "]");		
				
		sx1[i] = Relation.unary("sx1[" + i + "]");
		sx2[i] = Relation.unary("sx2[" + i + "]");
			
		for(int j = 0; j < 4; j++) {
			mi[i][j] = Relation.unary("mi[" + i + ", " + j + "]");
			si[i][j] = Relation.unary("si[" + i + ", " + j + "]");
		}
	}
	this.idx = Relation.unary("idx");
	this.succ = Relation.binary("succ");	
	for(int i = 0; i <= 16; i++) {
		ints[i] = IntConstant.constant(i).toExpression();
	}
	
}
 
Example #12
Source File: FloatExpressionTests.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private void testMultiply(float l, float r) {
	IntExpression lv = IntConstant.constant(Float.floatToIntBits(l));
	IntExpression rv = IntConstant.constant(Float.floatToIntBits(r));
	
	IntExpression computedSum = floatMultiply(lv, rv);
	IntExpression expectedSum = IntConstant.constant(Float.floatToIntBits(((float)l)*((float)r)));

	System.err.println(eval.evaluate(computedSum));
	dumpFloat(computedSum, "computed");
	dumpFloat(expectedSum, "expected");
	
	dumpFloat(lv, "left");
	dumpFloat(rv, "right");

	Assert.assertEquals("expected " + eval.evaluate(expectedSum) + " but got " + eval.evaluate(computedSum), eval.evaluate(expectedSum), eval.evaluate(computedSum));
}
 
Example #13
Source File: BlockedNQueens2.java    From kodkod with MIT License 6 votes vote down vote up
/**
	 * Prints the given solution using the given options to the console
	 */
	void print(Instance instance, Options options) {
		final Evaluator eval = new Evaluator(instance, options);
		final int n = instance.universe().size();
		for(int i = 0; i < n; i++) { 
			Expression x = IntConstant.constant(i).toExpression();
			for(int j = 0; j < n; j++) { 
				Expression y = IntConstant.constant(j).toExpression();
				if (eval.evaluate(x.product(y).in(queen))) { 
					System.out.print(" Q");
				} else {
					System.out.print(" .");
				}
			}
			System.out.println();
		}
//		System.out.println(instance); 
	}
 
Example #14
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static IntExpression intToFloat(IntExpression intValue) {
	IntExpression abs = intValue.abs();
	IntExpression maxSetBit = maxSetBit(abs);
	Formula shiftRight = maxSetBit.gt(IntConstant.constant(mantissaBits));
	
	IntExpression re = maxSetBit.minus(IntConstant.constant(mantissaBits));
	IntExpression adjustRight = adjustRight(abs, re);
	
	IntExpression le = IntConstant.constant(mantissaBits).minus(maxSetBit);
	IntExpression adjustLeft = abs.shl(le);

	IntExpression mantissa = 
		shiftRight.thenElse(adjustRight, adjustLeft).xor(implicitOne);
		
	IntExpression exponent = maxSetBit.plus(IntConstant.constant(exponentBias));
				
	IntExpression sign = intValue.lt(IntConstant.constant(0))
			.thenElse(IntConstant.constant(1<<(exponentBits+mantissaBits)), zero);

	return intValue.eq(zero)
		.thenElse(zero,
			sign.or(exponent.shl(IntConstant.constant(mantissaBits))).or(mantissa));
}
 
Example #15
Source File: NQueens.java    From kodkod with MIT License 6 votes vote down vote up
/**
		 * Prints the given solution
		 */
		void print(Instance instance, Options options) {
			final Evaluator eval = new Evaluator(instance, options);
			for(int i = 0; i < n; i++) { 
				Expression ci = IntConstant.constant(i).toExpression();
				for(int j = 0; j < n; j++) { 
					Expression cj = IntConstant.constant(j).toExpression();
					if (eval.evaluate(x.join(ci).intersection(y.join(cj)).some())) { 
						System.out.print(" Q");
					} else {
						System.out.print(" .");
					}
				}
				System.out.println();
			}
//			System.out.println(instance); 
		}
 
Example #16
Source File: Transpose4x4UnaryL.java    From kodkod with MIT License 6 votes vote down vote up
public Transpose4x4UnaryL() {
	for(int i = 0; i < 4; i++) {
		mx1[i] = Relation.unary("mx1[" + i + "]");
		mx2[i] = Relation.unary("mx2[" + i + "]");			
		sx1[i] = Relation.unary("sx1[" + i + "]");
		sx2[i] = Relation.unary("sx2[" + i + "]");
		for(int j = 0; j < 4; j++) {
			mi[i][j] = Relation.unary("mi[" + i + ", " + j + "]");
			si[i][j] = Relation.unary("si[" + i + ", " + j + "]");
		}
	}
	this.succ = Relation.binary("succ");	
	for(int i = 0; i < 16; i++) {
		ints[i] = IntConstant.constant(i).toExpression();
	}
	
}
 
Example #17
Source File: NQueens.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Prints the given solution
 */
void print(Instance instance, Options options) { 
	final Evaluator eval = new Evaluator(instance, options);
	for(int i = 0; i < n; i++) { 
		IntExpression ci = IntConstant.constant(i);
		for(int j = 0; j < n; j++) { 
			IntExpression cj = IntConstant.constant(j);
			Variable q = Variable.unary("q");
			if (eval.evaluate(q.join(x).sum().eq(ci).and(q.join(y).sum().eq(cj)).forSome(q.oneOf(queen)))) { 
				System.out.print(" Q");
			} else {
				System.out.print(" .");
			}
		}
		System.out.println();
	}
}
 
Example #18
Source File: FloatExpressionTests.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private void testReciprocalInitial(float v) {
	IntExpression ve = IntConstant.constant(Float.floatToIntBits(v));

	ve = floatAbs(ve);
	ve = ve.and(IntConstant.constant(exponentMask).not()).or(minusOne.plus(IntConstant.constant(exponentBias)).shl(IntConstant.constant(mantissaBits)));
	v = Float.intBitsToFloat(eval.evaluate(ve));
	
	IntExpression pe = floatMultiply(
		IntConstant.constant(Float.floatToIntBits(((float)32)/((float)17))), 
		ve);
	IntExpression xi = 
			floatMinus(
				IntConstant.constant(Float.floatToIntBits(((float)48)/((float)17))), 
				pe);

	float p = (((float)32)/((float)17))*v;
	float x0 = (float)48/(float)17 - p;		
	IntExpression x0e = IntConstant.constant(Float.floatToIntBits(x0));

	Assert.assertEquals(eval.evaluate(IntConstant.constant(Float.floatToIntBits(p))), eval.evaluate(pe));		
	Assert.assertEquals(eval.evaluate(x0e), eval.evaluate(xi));
}
 
Example #19
Source File: TranslateAlloyToKodkod.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object visit(ExprConstant x) throws Err {
    switch (x.op) {
        case MIN :
            return IntConstant.constant(min); // TODO
        case MAX :
            return IntConstant.constant(max); // TODO
        case NEXT :
            return A4Solution.KK_NEXT;
        case TRUE :
            return Formula.TRUE;
        case FALSE :
            return Formula.FALSE;
        case EMPTYNESS :
            return Expression.NONE;
        case IDEN :
            return Expression.IDEN.intersection(a2k(UNIV).product(Expression.UNIV));
        case STRING :
            Expression ans = s2k(x.string);
            if (ans == null)
                throw new ErrorFatal(x.pos, "String literal " + x + " does not exist in this instance.\n");
            return ans;
        case NUMBER :
            int n = x.num();
            // [am] const
            // if (n<min) throw new ErrorType(x.pos, "Current bitwidth is
            // set to "+bitwidth+", thus this integer constant "+n+" is
            // smaller than the minimum integer "+min);
            // if (n>max) throw new ErrorType(x.pos, "Current bitwidth is
            // set to "+bitwidth+", thus this integer constant "+n+" is
            // bigger than the maximum integer "+max);
            return IntConstant.constant(n).toExpression();
    }
    throw new ErrorFatal(x.pos, "Unsupported operator (" + x.op + ") encountered during ExprConstant.accept()");
}
 
Example #20
Source File: FloatExpressionTests.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
private void testCastToFloat(int i) {		
	IntExpression cast = intToFloat(IntConstant.constant(i));
	int floatBits = Float.floatToIntBits((float)i);
	IntExpression raw = IntConstant.constant(floatBits);
	
	Assert.assertTrue("expected " + eval.evaluate(raw) + " but got " + eval.evaluate(cast), eval.evaluate(cast.eq(raw)));
}
 
Example #21
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static IntExpression floatDivide(IntExpression l, IntExpression r) {
	IntExpression sign = sign(l).xor(sign(r));
	
	l = floatAbs(l);
	IntExpression le = exponent(l).minus(exponent(r).plus(one)).plus(IntConstant.constant(exponentBias));
	l = l.and(IntConstant.constant(exponentMask).not()).or(le.shl(IntConstant.constant(mantissaBits)));
	
	r = floatAbs(r);
	r = r.and(IntConstant.constant(exponentMask).not()).or(minusOne.plus(IntConstant.constant(exponentBias)).shl(IntConstant.constant(mantissaBits)));
	
	IntExpression xi = 
		floatMinus(
			IntConstant.constant(Float.floatToIntBits((float)48/(float)17)), 
			floatMultiply(
				IntConstant.constant(Float.floatToIntBits((float)32/(float)17)), 
				r));
	
	IntExpression two = IntConstant.constant(Float.floatToIntBits(2f));
	
	// find out why this does not work...
	//int steps = newtonSteps(bitWidth);
	for(int i = 0; i < 7; i++) {
		xi = floatMultiply(xi, floatMinus(two, floatMultiply(r, xi)));
	}
	
	IntExpression answer = floatMultiply(xi, l);
	return answer.and(IntConstant.constant(signMask).not()).or(sign.shl(IntConstant.constant(exponentBits+mantissaBits)));
}
 
Example #22
Source File: OverflowNumTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
protected int exeKodkodDef(int i, int j) {
    IntExpression kkIntExpr = kodkodOpExpr(IntConstant.constant(i), IntConstant.constant(j));
    Expression kkExpr = kkIntExpr.toExpression();
    Formula f = ret.eq(kkExpr.some().thenElse(kkIntExpr.toExpression(), IntConstant.constant(DEF_VAL).toExpression()));
    Solution sol = solve(f);
    return eval(sol.instance());
}
 
Example #23
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    setupOptions();
    setupBounds();

    ZERO = IntConstant.constant(0);
    MININT = IntConstant.constant(min(bw));
    MAXINT = IntConstant.constant(max(bw));
    a = Variable.unary("a");
    b = Variable.unary("b");
    as = a.sum();
    bs = b.sum();
    decls = a.oneOf(Expression.INTS).and(b.oneOf(Expression.INTS));
}
 
Example #24
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * all s : set univ | #s >= 0 !some(s : set univ | #s < 0)
 */
@Test
public void testCardinality0() {
    Variable s = Variable.unary("s");
    Formula f = (s.count().gte(IntConstant.constant(0))).forAll(s.setOf(Expression.UNIV));
    checkTrue(f);

    f = (s.count().lt(IntConstant.constant(0))).forSome(s.setOf(Expression.UNIV)).not();
    checkTrue(f);
}
 
Example #25
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * all s : set univ | (some s) iff #s > 0
 */
@Test
public void testCardinality1() {
    Variable s = Variable.unary("s");
    Formula f = s.some().iff(s.count().gt(IntConstant.constant(0))).forAll(s.setOf(Expression.UNIV));
    checkTrue(f);
}
 
Example #26
Source File: TranslateKodkodToJava.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void visit(IntConstant x) {
    String newname = makename(x);
    if (newname == null)
        return;
    file.printf("IntExpression %s=IntConstant.constant(%d);%n", newname, x.value());
}
 
Example #27
Source File: Simplifier.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/** @return canonical integer constant with the given value. */
final IntConstant constant(int val) { 
	IntConstant ret = constants.get(val);
	if (ret==null) {
		ret = IntConstant.constant(val);
		constants.put(val, ret);
	}
	return ret;
}
 
Example #28
Source File: Viktor.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Returns the sum of the elements in x (conditional on the non-emptiness of a 
 * given a[i]) located at indices [lo..hi]
 * @return the sum of cardinalities of the elements in x (conditional on the non-emptiness of a 
 * given a[i]) located at indices [lo..hi]
 */
private static IntExpression conditionalSum(Expression[] a, Expression[] x, int lo, int hi) {
	if (lo>hi)
		return IntConstant.constant(0);
	else if (lo==hi) 
		return a[lo].some().thenElse(x[lo].sum(), IntConstant.constant(0));
	else {
		final int mid = (lo + hi) / 2;
		final IntExpression lsum = conditionalSum(a, x, lo, mid);
		final IntExpression hsum = conditionalSum(a, x, mid+1, hi);
		return lsum.plus(hsum);
	}
}
 
Example #29
Source File: Viktor.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Returns the equations to be satisfied.
 * @return equations to be satisfied.
 */
public final Formula equations() {
	
	// each b <= cols-1
	Formula f0 = Formula.TRUE;
	final IntConstant colConst = IntConstant.constant(cols-1);
	for(IntExpression bi: b) {
		f0 = f0.and(bi.lte(colConst));
	}
	
	final Variable[] y = new Variable[rows];
	for(int i = 0; i < rows; i++) {
		y[i] = Variable.unary("y"+i);
	}
	
	Decls decls = y[0].oneOf(INTS);
	for(int i = 1; i < rows; i++)
		decls = decls.and(y[i].oneOf(INTS));
	
	Formula f1 = Formula.TRUE;
	final Expression[] combo = new Expression[rows];
	for(int i = 0; i < cols; i++) {
		for(int j = i+1; j < cols; j++) {
			for(int k = j+1; k < cols; k++) {
				Formula f2 = Formula.TRUE;
				for(int m = 0; m < rows; m++) {
					combo[0] = a[m][i];
					combo[1] = a[m][j];
					combo[2] = a[m][k];
					f2 = f2.and(conditionalSum(combo, y, 0, rows-1).eq(b[m]));
				}
				f1 = f1.and(f2.not().forAll(decls));
			}
		}
	}
	return f0.and(f1); 
}
 
Example #30
Source File: GroupScheduling.java    From kodkod with MIT License 5 votes vote down vote up
public Formula schedule() {
	final Variable p = Variable.unary("p"), r = Variable.unary("r"), g = Variable.unary("g");
	final Formula f0 = r.join(p.join(assign)).one().forAll(p.oneOf(person).and(r.oneOf(round)));
	final Formula f1 = assign.join(g).join(r).count().eq(IntConstant.constant(ng)).forAll(r.oneOf(round).and(g.oneOf(group)));
	final Variable pp = Variable.unary("p'");
	final Formula f2 = p.join(assign).intersection(pp.join(assign)).some().forAll(p.oneOf(person).and(pp.oneOf(person.difference(p))));
	return Formula.and(f0, f1, f2);
}